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.
source share