Exchange of mutable variables between threads in rust

Is it possible to use a mutable variable between multiple threads in Rust? Given the following:

fn main() { let mut msg = "Hi"; // ... msg = "Hello, World!"; do spawn { println(msg); } do spawn { println(msg); } } 

I get this error:

error

The variable just needs to be read-only for spawned threads. The variable should be mutable, though, because what I'm really trying to do is share the HashMap between multiple threads. As far as I know, there is no way to populate the HashMap unless it is modified. Even if there is a way to do this, I'm still interested in how to achieve something like this in general.

Thanks!

+6
source share
3 answers

This restriction is planned to be removed in a future version of the language. However, you can solve this problem with let msg = msg; before the first do spawn . This will move the msg value to a fixed location, effectively changing its variability.

+8
source

In case of sharing the string "Hello, World!" you just need to move the variable back to an immutable place (for example, "let mut msg = .....; let msg = msg;").

You may also want to not make a separate copy of the hash map for each stream that receives it, but in this case you also want to place it inside the ARC (with atomic link counted wrapper), which you will find in extra::arc .

+3
source

The answer "in general" (about saving a hash table that is mutable when used together) is that it is not directly possible; Rust was specifically designed to prohibit sharing a mutable state, to avoid certain types of errors and to protect certain types of security (and for other reasons).

However, you can create something similar to a common modified hash table. Imagine that one task has a mutable hash table. You can write the code so that other tasks can send him messages that said: "Update the hash table so that 5 maps to 18" or "Tell me that there are 7 maps."

What does this indirection do? Firstly, by copying values ​​into messages, it is impossible for another task to trample all the memory that you find in the middle of reading (a big security problem), and secondly, by writing code indirectly, it is more clear to the programmer that it is and is not atomic operation; the programmer will know that one should not expect that two consecutive messages about the contents of the hash table do not necessarily refer to the same version of the hash table, an assumption that is perfectly true (at least in Rust, due to some other restrictions) about two consecutive reads from an unpartitioned, mutable hash table.

+3
source

Source: https://habr.com/ru/post/950377/


All Articles