Sharing Mutable Variables Between Threads In Rust
In the case of sharing the string "Hello, World!"
, you'd just need to move the variable back into an immutable location (e.g., let mut msg = .....; let msg = msg;
).
Probably you also want to avoid making a separate copy of the hashmap for each thread that's receiving it, though, in which case you'll want to also put it inside an std::sync::Arc
(atomically reference counted wrapper).
This restriction is slated to be removed in a future version of the language. That said, you can fix this problem with let msg = msg;
before the first do spawn
. That will move the value msg
into an immutable location, effectively changing its mutability.
The "in general" answer (about keeping a hash table mutable while it's shared) is that it's not directly possible; Rust was specifically designed to forbid the sharing of mutable state in order to avoid certain kinds of bugs and to protect certain kinds of safety (and for other reasons).
However, it is possible to create something much like a shared mutable hash table. Imagine that a single task has a mutable hash table. You can write code so that other tasks can send it messages saying, essentially "Update the hash table so that 5 maps to 18" or "Tell me what 7 maps to".
What does this indirection accomplish? First, by copying values into messages, it's not possible for another task to trample all over memory that you're in the middle of reading (a big safety problem), and second, by writing the code indirectly, it's more clear to the programmer what is and is not an atomic operation; the programmer will know not to expect that two consecutive messages about hash table contents aren't necessarily about the same version of the hash table, an assumption that is perfectly valid (at least in Rust, thanks to some other restrictions) about two consecutive reads from an unshared, mutable, hash table.