websockets-rs / rust-websocket

A WebSocket (RFC6455) library written in Rust
http://websockets-rs.github.io/rust-websocket/
MIT License
1.55k stars 223 forks source link

Compile Errors When Trying To Use Core.run in a Spawned Thread #163

Closed git-blame closed 6 years ago

git-blame commented 6 years ago

First of all, I want to say I've just started experimented with Rust so I apologize if there are obvious design decisions in rust or this crate that make the following issue just a dumb newbie mistake.

I decided to make a simple change to examples/async-client.rs by simply wrapping the runner/core.run code in another spawned thread call. The idea being that the main thread is now free to do other things instead of blocking on core.run(runner).unwrap().

diff --git a/examples/async-client.rs b/examples/async-client.rs
index 999f5906..a1b09cab 100644
--- a/examples/async-client.rs
+++ b/examples/async-client.rs
@@ -44,6 +44,7 @@ fn main() {
                }
        });

+    thread::spawn(move || {
        let runner = ClientBuilder::new(CONNECTION)
                .unwrap()
                .add_protocol("rust-websocket")
@@ -62,4 +63,7 @@ fn main() {
                              .forward(sink)
                });
        core.run(runner).unwrap();
+    });
+    // TODO
+    println!("Doing Some More Stuff");
 }

Instead I get the following compilation errors:

error[E0277]: the trait bound `std::rc::Rc<std::cell::RefCell<tokio_core::reactor::Inner>>: std::marker::Send` is not satisfied in `[closure@examples/async-client.rs:47:19: 66:6 core:tokio_core::reactor::Core, stdin_ch:futures::sync::mpsc::Receiver<websocket::OwnedMessage>]`
  --> examples/async-client.rs:47:5
   |
47 |     thread::spawn(move || {
   |     ^^^^^^^^^^^^^ `std::rc::Rc<std::cell::RefCell<tokio_core::reactor::Inner>>` cannot be sent between threads safely
   |
   = help: within `[closure@examples/async-client.rs:47:19: 66:6 core:tokio_core::reactor::Core, stdin_ch:futures::sync::mpsc::Receiver<websocket::OwnedMessage>]`, the trait `std::marker::Send` is not implemented for `std::rc::Rc<std::cell::RefCell<tokio_core::reactor::Inner>>`
   = note: required because it appears within the type `tokio_core::reactor::Core`
   = note: required because it appears within the type `[closure@examples/async-client.rs:47:19: 66:6 core:tokio_core::reactor::Core, stdin_ch:futures::sync::mpsc::Receiver<websocket::OwnedMessage>]`
   = note: required by `std::thread::spawn`
git-blame commented 6 years ago

Moving creation of Core into thread::spawn removes error.