【发布时间】:2023-01-30 05:55:40
【问题描述】:
我正在阅读 Rust 中的并发性,因此创建了一个 cargo lib 来测试代码。我写了这个基本功能
use std::thread;
fn main() {
thread::spawn( || {
// I created 20 lines of print statements in thread, none prints out
println!("Hello 1, world thread!");
println!("Hello 2, world thread!");
println!("Hello 3, world thread!");
});
// also 20 lines here, they all executed
println!("Hello 1, world main function!");
println!("Hello 2, world main function!");
}
代码编译,只有thread之后的打印语句被记录在终端上。我多次运行cargo run,但结果仍然相同。
为了增加线程切换的机会,在线程内,我有 20 行打印语句,我也在线程外放了 20 行打印语句。但是线程日志中没有任何打印语句。我希望看到来自 spawn 线程和主线程的混合日志。
我想测试一下,当我有太多打印语句时,我会看到一些从 spawn 线程打印出来,一些从主线程以混合顺序打印出来。但我没有看到任何来自spawn thread 的打印输出。我可以用
use std::thread;
use std::time::Duration;
thread::sleep(Duration::from_millis(1));
或join.handle
但我不明白为什么我一开始看不到预期的行为
我正在使用 Kali Linux。我怀疑这可能与我的 linux 操作系统有关,但我在网上找不到与此相关的任何内容。
【问题讨论】:
标签: multithreading rust concurrency