nco*_*ish 3 multithreading rust
我正在为 Rust 编写一个 Phoenix 客户端库,利用rust-websockets 的异步 websocket 客户端。现在我无法弄清楚如何将回调函数传递到处理 websocket 流量的线程中。我有一个简化的结构:
pub struct Socket {
endpoint: String,
connected: Arc<AtomicBool>,
state_change_close: Option<Box<FnMut(String)>>,
}
Run Code Online (Sandbox Code Playgroud)
该结构体的connect
功能如下:
pub fn connect(&mut self) -> Result<(), String> {
if self.connected.load(Ordering::Relaxed) {
return Ok(())
}
// Copy endpoint string, otherwise we get an error on thread::spawn
let connection_string = self.endpoint.clone();
let (usr_msg, stdin_ch) = mpsc::channel(0);
let connection_thread = thread::spawn(move || {
// tokio core for running event loop
let mut core = Core::new().unwrap();
let runner = ClientBuilder::new(&connection_string)
.unwrap()
.add_protocol("rust-websocket")
.async_connect_insecure(&core.handle())
.and_then(|(duplex, _)| {
let (sink, stream) = duplex.split();
stream.filter_map(|message| {
println!("Received Message: {:?}", message);
match message {
OwnedMessage::Close(e) => {
// This is the line where I am trying to call the callback
if let Some(ref mut func) = self.state_change_close {
(func)(e.unwrap().reason);
}
Some(OwnedMessage::Close(e))
},
_ => None,
}
})
.select(stdin_ch.map_err(|_| WebSocketError::NoDataAvailable))
.forward(sink)
});
// Start the event loop
core.run(runner).unwrap();
});
self.connected.store(true, Ordering::Relaxed);
return Ok(())
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译此代码时,出现以下错误:
error[E0277]: the trait bound `std::ops::FnMut(std::string::String) + 'static: std::marker::Send` is not satisfied
--> src\socket.rs:99:29
|
99 | let connection_thread = thread::spawn(move || {
| ^^^^^^^^^^^^^ the trait `std::marker::Send` is not implemented for `std::ops::FnMut(std::string::String) + 'static`
|
Run Code Online (Sandbox Code Playgroud)
我尝试将 的类型更改state_change_close
为 aMutex<Option<...>>
以避免线程安全问题,但这对解决此问题没有帮助。我想做的事情可能吗?
经过更多研究后,我意识到我只需修改Option<Box<FnMut(String)>>
为Option<Box<FnMut(String) + Send>>
并将其复制到我的代码周围可能设置回调的任何地方。了解有关特质对象的更多信息!