我需要暂停 Rust 中的当前线程并从另一个线程通知它。在Java中我会写:
synchronized(myThread) {
myThread.wait();
}
并从第二个线程(恢复主线程):
synchronized(myThread){
myThread.notify();
}
在 Rust 中可以做同样的事情吗?
使用发送类型的通道()
可能是最简单的:
use std::sync::mpsc::channel;
use std::thread;
let (tx,rx) = channel();
// Spawn your worker thread, giving it `send` and whatever else it needs
thread::spawn(move|| {
// Do whatever
tx.send(()).expect("Could not send signal on channel.");
// Continue
});
// Do whatever
rx.recv().expect("Could not receive from channel.");
// Continue working
The ()
类型是因为它实际上是零信息,这意味着很明显您只是将其用作信号。事实上,它的大小为零意味着它在某些情况下也可能更快(但实际上可能不会比正常的机器字写入快)。
如果你只是需要通知程序有一个线程done,你可以抓住它的加入守卫并等待它加入。
let guard = thread::spawn( ... ); // This will automatically join when finished computing
guard.join().expect("Could not join thread");
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)