Achieving concurrency with shared state
In this section, we'll discuss the second model of concurrent programming supported in the Rust Standard Library – the shared-state or shared-memory model of concurrency. Recall that all threads in a process share the same process memory space, so why not use that as a way to communicate between threads, rather than message-passing? We'll look at how to achieve this using Rust.
A combination of Mutex
and Arc
constitutes the primary way to implement shared-state concurrency. Mutex
(mutual exclusion lock) is a mechanism that allows only one thread to access a piece of data at one time. First, a data value is wrapped in a Mutex
type, which acts as a lock. You can visualize Mutex
like a box with an external lock, protecting something valuable inside. To access what's in the box, first of all, we have to ask someone to open the lock and hand over the box. Once we're done, we hand over the box back and someone else asks...