An easy approach to thinking about how threads work.

Threads are more easily thought of graphically (at least I think so). We start with our main thread:

Figure 2

The main thread goes from the start of the application to the end of the application.

At any point on our main thread, we can create a new thread (or new threads, if required).

Figure 3

These two new threads can do anything the application needs them to do. There is a simple rule though: The threads can only last as long the application does. As Figure 3 shows, the threads start and carry on their merry way; there is nothing to say the thread has to rejoin the main thread, nor is there any rule to say at what point the thread returns (which can cause some very large thread safety issues, leading to panics).

It goes without saying that each thread can also spawn their own threads to perform sub-processes:

Figure 4

If you're accustomed to threading in the likes of C, C++, and C#, you'll already know that a thread can return to the main thread at any time and that this at any time can be disastrous to the safe running of the application. It is different in Rust.

When a thread in Rust is spawned from either the main thread (or any subthread) a handle is created. Rust then uses this token to retrieve the thread at a given point; therefore, the issue of a race condition (where one thread returns before another, leading to crashes) is essentially removed.

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

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