Rust Multithread

#rust-lang #programming

Arc is a thread safe reference counting pointer which stands for 'atomically reference counted'. With Arc, one can share ownership of data between threads.

let shared_data = Arc::new(0);

If you want to have mutable variables, you can combine it with Mutex.

let shared_mutable_data = Arc::new(Mutex::new(0));
let cloned = Arc::clone(&shared_mutable_data);
thread::spawn(move || {
    *cloned.lock().unwrap() = 1;
});

But if you just want to share primitives(i32, f32, ...) read about atomic

What is an atomic operation?

An atomic operation is an operation that can not be divided into steps. For example, setting most of the primitives in most programming lanugages is atomic. Which means, another thread can not read the state while the operation still continuing. In other words, an atomic operation is either not started or finished from the perspective of another thread. For example in a 32-bit system, writing long is not an atomic operation because the system first writes the first 32 bits and then the second 32 bits. A thread can read the state of this variable in the middle of the progress. To make operations atomic we use locks, mutex etc.

back
top