【问题标题】:Why print statements inside rust `thread` do not run?为什么 rust `thread` 中的打印语句不运行?
【发布时间】: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


    【解决方案1】:

    当主线程结束时程序退出。我们不能确定哪个线程会先退出,但很可能是已经在运行的线程。您可以让主线程等待其他线程完成,方法是使用新线程的JoinHandle 等到它完成后再退出程序。

    use std::thread;
    
    fn main() {
        let join_handle = thread::spawn( || {
            println!("Hello 1, world  thread!");
            println!("Hello 2, world  thread!");
            println!("Hello 3, world  thread!");
        });
        println!("Hello 1, world main function!");
        println!("Hello 2, world main function!");
        
        // Wait until other thread has finished
        join_handle.join().expect("thread did not panic");
    }
    

    Rust Playground

    【讨论】:

    • 我在线程内添加了 20 行,在线程外添加了 20 行,但是打印语句都没有在线程内运行。这不奇怪吗?
    • @Yilmaz 听起来你不知何故陷入了僵局。如果我不得不猜测,您可能在两个线程上都锁定了一个互斥量。如果我是正确的,您需要确保它在尝试加入线程之前被删除(它在范围的末尾被删除,所以要么将它放在一个单独的代码块中,要么显式地drop(guard))。您的操作系统不应对此产生任何影响。
    • @Yilmaz The code in the answer works fine. 请使用您遇到问题的真实代码编辑问题。
    • @ColonelThirtyTwo 我想测试一下,当我有太多打印语句时,我会看到一些从 spawn 线程打印出来,一些从主线程以混合顺序打印出来。我会相应地更新问题
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2010-11-06
    • 2013-05-04
    • 1970-01-01
    • 2018-05-16
    • 2014-02-16
    相关资源
    最近更新 更多