为什么某些语句在线程中运行时无法执行? [英] Why do some statements fail to execute when run in a thread?

查看:98
本文介绍了为什么某些语句在线程中运行时无法执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解此代码示例的程序行为:

use std::comm;
use std::thread::Thread;

static NTHREADS: uint = 3;

fn main() {
    let (tx, rx): (Sender<uint>, Receiver<uint>) = comm::channel();

    for id in range(0, NTHREADS) {
        let thread_tx = tx.clone();

        Thread::spawn(move || {
            thread_tx.send(id);
            println!("thread {} finished", id);
        }).detach();
    }

    let mut ids = Vec::with_capacity(NTHREADS);
    for _ in range(0, NTHREADS) {
        ids.push(rx.recv());
    }

    println!("{}", ids);
}

具体来说,我不明白为什么某些任务在分离时无法到达此行:

Specifically, I don't understand why some tasks fail to reach this line when being detached:

println!("task {} finished", id);

但当与父母(主要)加入时不是.

But not when when joined with the parent (main).

还有,为什么只按预先定义的顺序执行加入的任务?

Also, why is it that only joined tasks are executed in pre-defined order?

推荐答案

您需要多次运行代码,因为不能保证线程的执行顺序.我也不知道允许在线评估有多少个并发处理器,因此您可能在单核计算机上运行它.我在多核笔记本电脑上运行了几次,并得到以下输出:

You need to run the code multiple times because the order of execution of the threads is not guaranteed. I also don't know how many concurrent processors that online evaluation is allowed, so you might be running it in a single-core machine. I ran it a few times on my multi-core laptop and got the following output:

task 0 finished
task 1 finished
task 2 finished
[0, 1, 2]

task 1 finished
task 0 finished
task 2 finished
[0, 1, 2]

task 0 finished
task 1 finished
[0, 1, 2]
task 2 finished

线程的一个重要考虑因素是程序在主线程完成时完成 .在这种情况下,要考虑4个线程:主线程和3个任务线程.一旦收到3条消息并将其打印出来,主线程将完成.其余线程在做什么都没关系!

An important consideration with threads is that the program finishes when the main thread finishes. In this case, there are 4 threads to consider: the main thread and 3 task threads. The main thread will be done once it has received 3 messages and printed them out. It doesn't matter what the rest of the threads are doing!

当您从主线程中join一个线程时,您正在告诉主线程等待,直到辅助线程退出.这意味着每个线程将能够在程序退出之前执行println!.

When you join a thread from the main thread, you are telling the main thread to wait until the worker thread has exited. This means that each thread will be able to execute the println! before the program exits.

这篇关于为什么某些语句在线程中运行时无法执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆