Why are some statements not executed when starting in a thread?

I find it difficult to understand the behavior of the program in this sample code :

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); } 

In particular, I don't understand why some tasks cannot reach this line when disconnected:

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

But not when it is connected to the parent (primary).

In addition, why only nested tasks are performed in a predetermined order?

+2
source share
2 answers

You need to run the code several times because the execution order of the threads is not guaranteed. I also do not know how many parallel processors allow online evaluation, so you can run it in a single-core machine. I ran it several 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 

An important consideration for threads is that the program ends when the main thread ends. In this case, it is necessary to consider 4 threads: the main thread and 3 task threads. The main thread will be executed as soon as it receives 3 messages and prints them. It doesn't matter what the rest of the topics do!

When you join thread from the main thread, you are telling the main thread to wait until the worker thread exits. This means that every thread will be able to execute println! before the release of the program.

+1
source

This code does not attach to tasks, but separates it. This means that tasks are independent of the main thread (the one that separates it)

Then two parameters for each task:

  • it is completed before println is executed: then you see it in the code using print
  • it is not finished, and then println you subtract is executed without waiting for it

If you join, then I need to wait for this task to continue. Therefore, the entire task is performed before the line is completed.

There is no predefined order that makes multi-threaded code difficult to debug :-)

+1
source

Source: https://habr.com/ru/post/980606/


All Articles