Why does Rust have mutexes and other sychronization primitives if sharing mutable state between tasks is not allowed?

I understand that it's impossible to split mutable state between tasks in Rust, so why does Rust have things like mutexes in the language? What is their purpose?

+4
source share
2 answers

“Sharing mutable data between tasks is not allowed” is a simplification. No crime meant, it was also used in many introductory materials on Rust and for good reason. But the truth is, Rust just wants to get rid of data races; not sharing anything of the preferred approach, but not the only one. Rust also wants to be a system programming language in the same sense as C and C ++, so it will not be able to completely remove some features or optimize performance. However, in general, shared modified memory is unsafe (data races, etc.), so if you want to, you will have to accept responsibility by wrapping it in blocks unsafe.

, (, ). , - unsafe, (, , "" ), . : Rust. , Mutex , ( ), .

+13

Rust a Mutex

,

Mutex Mutex. mut :

use std::sync::{Arc, Mutex};
use std::thread;
use std::sync::mpsc::channel;

const N: usize = 10;

// Spawn a few threads to increment a shared variable (non-atomically), and
// let the main thread know once all increments are done.
//
// Here we're using an Arc to share memory among threads, and the data inside
// the Arc is protected with a mutex.
let data = Arc::new(Mutex::new(0));

let (tx, rx) = channel();
for _ in 0..10 {
    let (data, tx) = (data.clone(), tx.clone());
    thread::spawn(move || {
        // The shared state can only be accessed once the lock is held.
        // Our non-atomic increment is safe because we're the only thread
        // which can access the shared state when the lock is held.
        //
        // We unwrap() the return value to assert that we are not expecting
        // threads to ever fail while holding the lock.
        let mut data = data.lock().unwrap();
        *data += 1;
        if *data == N {
            tx.send(()).unwrap();
        }
        // the lock is unlocked here when `data` goes out of scope.
    });
}

rx.recv().unwrap();

Rust unsafe . - , Rust. , .

+5

Source: https://habr.com/ru/post/1538478/


All Articles