O'Reilly logo

Rust Essentials by Ivo Balbaert

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The shared mutable state

So, how can we make the not_shared.rs program give us the correct result? Rust provides tools, the so-called atomic types from the std::sync::atomic submodule, to handle shared mutable state safely. In order to share data, you need to wrap the data in some of the sync primitives, such as Arc, Mutex, RwLock, AtomicUSize, and so on.

Basically, the principle of locking is used, which is similar to that used by operating systems and database systems—exclusive access to a resource is given to the thread that has obtained a lock (which is also called a mutex and comes from mutually exclusive) on the resource. A lock can only be obtained by one thread at a time. In this way, two threads cannot change this resource at the same ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required