gpt4 book ai didi

multithreading - 从另一个线程调用 FnMut 回调

转载 作者:行者123 更新时间:2023-11-29 08:16:15 25 4
gpt4 key购买 nike

我正在为 Rust 编写一个 Phoenix 客户端库,利用来自 rust-websockets 的异步 websocket 客户端.现在我无法弄清楚如何将回调函数传递到处理 websocket 流量的线程中。我有一个简化的结构:

pub struct Socket {
endpoint: String,
connected: Arc<AtomicBool>,
state_change_close: Option<Box<FnMut(String)>>,
}

这个结构有一个 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(())
}

当我尝试编译这段代码时,出现以下错误:

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`
|

我试过改变 state_change_close 的类型到 Mutex<Option<...>>以避免线程安全问题,但这对解决这个问题没有帮助。我尝试做的事情可行吗?

最佳答案

在做了更多研究后,我意识到我只需要修改 Option<Box<FnMut(String)>>成为Option<Box<FnMut(String) + Send>>并将我的代码周围的代码复制到可能设置回调的任何地方。了解有关特征对象的更多信息!

关于multithreading - 从另一个线程调用 FnMut 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45311647/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com