gpt4 book ai didi

multithreading - 如何在 Rust 中同时运行不同的线程?

转载 作者:行者123 更新时间:2023-11-29 08:17:34 24 4
gpt4 key购买 nike

假设我有两个具有不同意图的线程(T1、T2)。 T1 负责将消息插入队列,T2 负责弹出消息。如何实现同时运行 T1 和 T2 的方法?

我尝试查看 Rust 中现有的多线程实现和示例,但其中大部分都是关于为同一作业生成多个线程。

//using an Arc object of an ArrayQueue
let handle1 = thread::spawn( move || {
//clone arc object
//push
});

let handle2 = thread::spawn( move || {
//clone arc object
//pop
});```

最佳答案

为什么你认为线程没有同时运行?为了在线程之间轻松传递数据,您可以使用标准库中的 MPSC channel :

use std::time::Duration;

fn main() {
let (sender, receiver) = std::sync::mpsc::channel();

let sending_thread = std::thread::spawn(move || {
for i in 0..10 {
println!("[{:?}] Sending: {}", std::thread::current().id(), i);
sender.send(i).unwrap();
std::thread::sleep(Duration::from_secs(1));
}
});

let receiving_thread = std::thread::spawn(move || {
for i in receiver {
println!("[{:?}] Received: {}", std::thread::current().id(), i);
}
});

let _ = sending_thread.join();
let _ = receiving_thread.join();
println!("Done");
}

关于multithreading - 如何在 Rust 中同时运行不同的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57831428/

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