Ste*_*nko 3 multithreading notify wait rust
我需要暂停Rust中的当前线程并从另一个线程通知它.在Java中我会写:
synchronized(myThread) {
myThread.wait();
}
Run Code Online (Sandbox Code Playgroud)
从第二个线程(恢复主线程):
synchronized(myThread){
myThread.notify();
}
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
这种()类型是因为它实际上是零信息,这意味着很明显你只是将它用作信号.它的大小为零的事实意味着它在某些情况下也可能更快(但实际上可能不比正常的机器字写入更快).
如果您只需要通知程序线程已完成,您可以获取其加入保护并等待它加入.
let guard = thread::spawn( ... ); // This will automatically join when finished computing
guard.join().expect("Could not join thread");
Run Code Online (Sandbox Code Playgroud)