gpt4 book ai didi

multithreading - 如何从另一个线程终止或挂起 Rust 线​​程?

转载 作者:行者123 更新时间:2023-11-29 07:42:24 32 4
gpt4 key购买 nike

Editor's note — this example was created before Rust 1.0 and the specific types have changed or been removed since then. The general question and concept remains valid.

我生成了一个内部有无限循环和计时器的线程。

thread::spawn(|| {
let mut timer = Timer::new().unwrap();
let periodic = timer.periodic(Duration::milliseconds(200));
loop {
periodic.recv();

// Do my work here
}
});

基于某些条件一段时间后,我需要从程序的另一部分终止该线程。换句话说,我想退出死循环。我怎样才能正确地做到这一点?另外,我怎样才能暂停这个线程并稍后恢复它?

我尝试使用全局不安全标志来打破循环,但我认为这个解决方案看起来不太好。

最佳答案

对于终止和挂起线程,您可以使用 channel 。

外部终止

在工作循环的每次迭代中,我们检查是否有人通过 channel 通知我们。如果是,或者如果 channel 的另一端超出范围,我们将打破循环。

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() 挂起线程,直到有东西到达 channel 。为了恢复线程,您需要通过 channel 发送一些东西;本例中的单位值 ()。如果 channel 的发送端掉线,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(());
}
}

其他工具

channel 是完成这些任务的最简单和最自然的 (IMO) 方式,但不是最有效的方式。您可以在 std::sync 中找到其他并发原语。模块。它们属于比 channel 更低的级别,但在特定任务中可以更有效率。

关于multithreading - 如何从另一个线程终止或挂起 Rust 线​​程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26199926/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com