Using message passing to transfer data between threads
The receiving end of a channel has two useful methods:
recv: block the main thread’s execution and wait until a value
is sent down the channel
try_recv: doesn’t block but will instead return a
Result<T, E> immediately: an Ok value holding a message if
one is available and an Err value if there aren’t any messages
this time
useful if the thread has other work to do while waiting
Channels and ownership transference
The send function takes ownership of its parameter, and when the
value is moved, the receiver takes ownership of it. This stops us
from accidentally using the value again after sending it.
Sending multiple values and seeing the receiver waiting
Producing multiple producers by cloning the transmitter
The output should look something like this:
Got: hi
Got: more
Got: from
Got: messages
Got: for
Got: the
Got: thread
Got: you
Shared-state concurrency
Using mutexes to allow access to data from one thread at a time
Mutex allows only one thread to access some data at any given time.
Mutex<T> is smart pointer.
Multiple ownership with multiple threads
Rc<T> is not safe to share across threads.
Atomic reference counting with Arc<T>
Arc<T> is a type like Rc<T> that is safe to use in concurrent situations.
Extensible concurrency with the Sync and Send traits
Allowing transference of ownership between threads with Send
The Send marker trait indicates that ownership of values of the
type implementing Send can be transferred between threads.
Allowing access from multiple threads with Sync
The Sync marker trait indicates that it is safe for the type
implementing Sync to be referenced from multiple threads.
Manually implementing these traits involves implementing unsafe
Rust code.