【发布时间】:2020-12-06 01:12:55
【问题描述】:
在这段代码 sn-p (playground link) 中,我们在两个线程之间进行了一些简单的通信。主线程(执行第二个async 块)将2 发送到async move 块中的线程2,后者接收它,添加自己的值,然后通过另一个通道将结果发送回主线程,主线程打印值。
线程 2 包含一些局部状态,thread_unsafe 变量,它既不是 Send 也不是 Sync,并通过 .await 维护。因此,我们正在创建的impl Future 对象本身既不是Send 也不是Sync,因此对pool.spawn_ok 的调用是一个编译错误。
但是,这似乎应该没问题。我理解为什么spawn_ok() 不能接受不是Send 的未来,我也理解为什么将异步块编译到状态机会导致结构包含非Send 值,但在这个例子我唯一想发送到另一个线程的是recv 和send2。如何表示future只有在发送后才切换到非线程安全模式?
use std::rc::Rc;
use std::cell::RefCell;
use futures::channel::oneshot::channel;
use futures::executor::{ThreadPool, block_on};
fn main() {
let pool = ThreadPool::new().unwrap();
let (send, recv) = channel();
let (send2, recv2) = channel();
pool.spawn_ok(async move {
let thread_unsafe = Rc::new(RefCell::new(40));
let a = recv.await.unwrap();
send2.send(a + *thread_unsafe.borrow()).unwrap();
});
let r = block_on(async {
send.send(2).unwrap();
recv2.await.unwrap()
});
println!("the answer is {}", r)
}
【问题讨论】:
标签: multithreading rust future