java暂停另一个线程_如何从另一个线程终止或暂停Rust线程?
對于終止和掛起線程,您可以使用通道 .
外部終止
在工作循環的每次迭代中,我們檢查是否有人通過渠道通知我們 . 如果是,或者如果通道的另一端超出范圍,我們就會打破循環 .
use std::io::{self, BufRead};
use std::sync::mpsc::{self, TryRecvError};
use std::thread;
use std::time::Duration;
fn main() {
println!("Press enter to terminate the child thread");
let (tx, rx) = mpsc::channel();
thread::spawn(move || loop {
println!("Working...");
thread::sleep(Duration::from_millis(500));
match rx.try_recv() {
Ok(_) | Err(TryRecvError::Disconnected) => {
println!("Terminating.");
break;
}
Err(TryRecvError::Empty) => {}
}
});
let mut line = String::new();
let stdin = io::stdin();
let _ = stdin.lock().read_line(&mut line);
let _ = tx.send(());
}
暫停和恢復
我們使用 recv() 暫停線程,直到某些東西到達通道 . 為了恢復該線程,您需要通過該 Channels 發送內容;在這種情況下單位值 () . 如果通道的發送端被丟棄, recv() 將返回 Err(()) - 我們使用它來退出循環 .
use std::io::{self, BufRead};
use std::sync::mpsc;
use std::thread;
use std::time::Duration;
fn main() {
println!("Press enter to wake up the child thread");
let (tx, rx) = mpsc::channel();
thread::spawn(move || loop {
println!("Suspending...");
match rx.recv() {
Ok(_) => {
println!("Working...");
thread::sleep(Duration::from_millis(500));
}
Err(_) => {
println!("Terminating.");
break;
}
}
});
let mut line = String::new();
let stdin = io::stdin();
for _ in 0..4 {
let _ = stdin.lock().read_line(&mut line);
let _ = tx.send(());
}
}
其他工具
Channels 是執行這些任務的最簡單,最自然(IMO)的方式,但不是最有效的方法 . 您可以在std::sync模塊中找到其他并發原語 . 它們屬于比通道更低的級別,但在特定任務中可以更有效 .
總結
以上是生活随笔為你收集整理的java暂停另一个线程_如何从另一个线程终止或暂停Rust线程?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php new static,PHP中n
- 下一篇: centos arm linux gcc