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