Threads
Last updated
Last updated
Rust provides built-in support for concurrent programming through its standard library module std::thread
.
We can spawn threads using std::thread::spawn
, which takes a closure and runs it in a new thread.
In a multi-threaded program, if we need shared mutable state, we can use:
Arc<T>
: An atomic reference-counted smart pointer for shared ownership across threads.
Mutex<T>
: A synchronization primitive for mutual exclusion to safely access shared data.
Rust provides channels for thread communication in the std::sync::mpsc
module.
mpsc::channel
creates a transmitter (Sender
) and a receiver (Receiver
).
Messages are sent via the transmitter and received via the receiver.
The Sender
can be cloned to send
to the same channel multiple times, but only one Receiver
is supported.
References:
In this exercise we just need to wait the spawned thread to finish, get the result, and push it into results
.
We can wait the thread to finish using join
method.
pub fn join(self) -> Result<T>
: Waits for the associated thread to finish. This function will return immediately if the associated thread has already finished.
In this exercise using Arc
doesn't work because we also need mutability.
So we should add Mutex
, A mutual exclusion primitive useful for protecting shared data.
Mutex will block threads waiting for the lock to become available. The mutex can be created via a new constructor. Each mutex has a type parameter which represents the data that it is protecting. The data can only be accessed through the RAII guards returned from
lock
andtry_lock
, which guarantees that the data is only ever accessed when the mutex is locked.
First we add mutex like this:
Then inside the spawned thread block we get lock
and update the jobs_done
like this:
To get the value for print we can do the same with as above:
In this exercise we learn how to use channel
.
Because we will use two thread to send data we need to clone
the Sender
and use it on the first thread.
The
Sender
can be cloned tosend
to the same channel multiple times, but only oneReceiver
is supported.