从另一个线程调用FnMut回调

时间:2017-07-25 19:06:49

标签: multithreading rust

我正在为Rust编写一个Phoenix客户端库,利用来自rust-websockets的async 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<...>>以避免线程安全问题,但这对此问题没有帮助。我试图做的是什么?

1 个答案:

答案 0 :(得分:1)

在做了一些更多的研究之后,我意识到我只需将Option<Box<FnMut(String)>>修改为Option<Box<FnMut(String) + Send>>并将我的代码复制到可以设置回调的所有地方。更多地了解特质对象!