Search code examples
multithreadingrustrust-obsolete

Sharing Mutable Variables Between Threads In Rust


Editor's note: This code example is from a version of Rust prior to 1.0 and is not syntactically valid Rust 1.0 code.

Is it possible to share 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 readonly to the spawned threads. The variable has to be mutable though, because what I'm really trying to do is share a HashMap between multiple threads. As far as I know there is no way to populate a HashMap unless it's mutable. Even if there is a way to do that though, I'm still interested in knowing how to accomplish something like this in general.

Thank you!


Solution

  • 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.