Hacker News new | ask | show | jobs
by maxbond 1364 days ago
There are mutexes & other synchronization primitives. The stdlib doesn't ship a thread safe Vec or HashMap, but there are many on offer from the community. Rust's stdlib is small; lots of functionality you might expect is in community provided libraries (at least presently - I imagine thread safe collections like that will be added in the future, when the community comes to a consensus about how they should look). This works out better than you might expect, and avoids hazards that say Python encounters, where parts of the stdlib are so bad there is no safe use case (looking at you, `csv.Sniffer`).

In Rust, there are traits (you might know them as interfaces or protocols from other languages) called Send and Sync which tell the language whether or not something can be send to a different thread, or shared between threads.

Vec<T> is Send but not Sync - you could pass ownership of it to a different thread, surrendering your access to it in the process, but two threads couldn't share access to it. Almost everything is Send, unless it contains references to some thread local state.

Mutex<Vec<T>> is Sync - you can share it between threads. Basically if you take the lock, you'll get back a smart pointer to your Vec<T>.

These traits are generally implemented automatically; you can implement them on a type yourself, using unsafe, but you'd only do that if you were writing your own synchronization primitives or thread safe data structures.

So; the compiler is able to infer which types are and are not thread safe, and what flavor of thread safety it has. It's then able to use that to check for thread safety violations at compile time.

There's more to it than that, in particular it's possible to share a read-only reference to a Vec<T> between threads (with a compile time guarantee that no one has a mutable reference to it), but I'd refer you to the book[1] or to other articles on HN of you wanted the specifics.

[1] https://doc.rust-lang.org/stable/book/