How it works...

We declared a static variable named NO_THREADS to which we assigned the 32-bit integer value 10; we also created an empty mutable vector named thread_holder.

Using a for loop, we iterated over the value, starting from 0 to the upper limit value of the static variable, that is, NO_THREADS. Inside the for loop, we pushed the spawned threads to the thread_holder vector using the push functionality. While creating the thread, we used the move closure and sent the iterator value i to the newly spawned thread.

Once all the thread-spawning commands are completed by the compiler, we start to iterate over the thread_holder vector elements using a for loop. In this case, the iterator variable was thread_elements; we called the join and unwrap function to the thread through this variable. With this, we ensured that all the threads are completed and they return to the main thread, where we print the value that was sent earlier to the thread when it was spawned.

Since all the threads are scheduled by the OS, we can't predict the order in which threads will be spawned and the values returned.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.87.161