Multithreading 如何在线程之间共享非发送对象?

Multithreading 如何在线程之间共享非发送对象?,multithreading,concurrency,rust,Multithreading,Concurrency,Rust,我想在并发程序中使用rustbox库。 但是,rustbox::rustbox没有实现Sendtrait,因此我不能在线程之间共享对象 extern crate rustbox; use std::thread; use std::sync::{ self, Arc, Mutex }; use std::default::Default; fn main() { let rustbox = match rustbox::RustBox::init(Default::default()

我想在并发程序中使用
rustbox
库。 但是,
rustbox::rustbox
没有实现
Send
trait,因此我不能在线程之间共享对象

extern crate rustbox;

use std::thread;
use std::sync::{ self, Arc, Mutex };
use std::default::Default;

fn main() {
    let rustbox = match rustbox::RustBox::init(Default::default())  {
        Ok(r) => r,
        _ => panic!(""),
    };

    let count = Arc::new(Mutex::new(0usize));
    let (tx, rx) = sync::mpsc::channel();
    let count_clone = count.clone();
    thread::scoped(move|| {
        loop {
            let _ = rx.recv().unwrap();
            show(&rustbox, count_clone.lock().unwrap().clone());
        }
    });
    loop {
        if let Ok(_) = rustbox.poll_event(false) {
            let mut i = count.lock().unwrap();
            *i += 1;
            show(&rustbox, i.clone());
        } else {
            tx.send(()).unwrap();
        }
    }
}

fn show(rustbox: &rustbox::RustBox, count: usize) {
    use rustbox::Color;
    rustbox.print(1, 1, rustbox::RB_BOLD, Color::Default, Color::Default, &format!("{}", count));
}
tx.send(()).unwrap()将出现在其他线程中

编译器错误消息为:

src/main.rs:16:5: 16:19 error: the trait `core::marker::Send` is not implemented for the type `rustbox::RustBox` [E0277]
src/main.rs:16     thread::scoped(move|| {
               ^~~~~~~~~~~~~~
src/main.rs:16:5: 16:19 note: `rustbox::RustBox` cannot be sent  between threads safely
src/main.rs:16     thread::scoped(move|| {
               ^~~~~~~~~~~~~~
error: aborting due to previous error
Could not compile `sof`.

由于您使用的是
作用域
线程,这些线程保证在
rustbox
之前死亡,因此如果rustbox是
Sync
,您只需共享对它的引用即可

如果它不是
Sync
,您只需将其包装在
互斥体中,并共享对该互斥体的引用即可

注意:这只可能是因为您使用的是
thread::scoped
,如果您使用的是
thread::spawned
,那么
Send
将是必需的

fn main() {
    let rustbox = match rustbox::RustBox::init(Default::default())  {
        Ok(r) => r,
        _ => panic!(""),
    };
    let rustbox = &rustbox;

    let count = Arc::new(Mutex::new(0usize));
    let (tx, rx) = sync::mpsc::channel();
    let count_clone = count.clone();
    thread::scoped(move|| {
        loop {
            let _ = rx.recv().unwrap();
            show(rustbox, count_clone.lock().unwrap().clone());
        }
    });
    loop {
        if let Ok(_) = rustbox.poll_event(false) {
            let mut i = count.lock().unwrap();
            *i += 1;
            show(rustbox, i.clone());
        } else {
            tx.send(()).unwrap();
        }
    }
}