I have some mutable state I need to share between threads. I followed the concurrency section of the Rust book, which shares a vector between threads and mutates it.
<I'm trying to understand why
M
would need to implementSend
, ...
Because, as stated by the Send documentation:
Types that can be transferred across thread boundaries.
If it's not Send
, it is by definition not safe to send to another thread.
Almost all of the information you need is right there in the documentation:
Send
.Send
if all the values it captures are Send
. This is true in general of most types (they are Send
if everything they're made of is Send
, and similarly for Sync
).data
, which is an Arc<T>, which is only Send
if T
is Send
.T
is a Mutex<U>, which is only Send
if U
is Send
.U
is M
. Thus, M
must be Send
.In addition, note that thread::spawn
also requires that the callable be 'static
, so you need that too. It needs that because if it didn't require that, it'd have no guarantee that the value will continue to exist for the entire lifetime of the thread (which may or may not outlive the thread that spawned it).
..., and what the appropriate way to accomplish this is.
Same way as any other constraints: M: 'static + Send + Memory
.