Threads in Rust
...

Thread, mutex e semafori sono concetti fondamentali per la gestione della concorrenza in Rust, così come in molti altri linguaggi di programmazione. In Rust, questi concetti sono implementati attraverso la libreria standard (std::sync) e altre librerie esterne come crossbeam.
In Rust, puoi creare un thread utilizzando il modulo std::thread. Ecco un esempio:

use std::thread;
use std::time::Duration;

fn main() {
    thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });
    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }
}
/* Output:
hi number 1 from the main thread!
hi number 1 from the spawned thread!
hi number 2 from the main thread!
hi number 2 from the spawned thread!
hi number 3 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the main thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread! */

Nota che il tuo output potrebbe essere diverso, in quanto la velocità di ogni thread è data dal tuo processore.
L'aspetto importante da notare è che il thread handle non ha completato l'esecuzione, perché ogni thread figlio termina con la fine del main. Per assicurarsi che handle completi l'esecuzione, si modifica il programma in questo modo:

use std::thread;
use std::time::Duration;

fn main() {
    let handle = thread::spawn(|| {
        for i in 1..10 {
            println!("hi number {} from the spawned thread!", i);
            thread::sleep(Duration::from_millis(1));
        }
    });

    for i in 1..5 {
        println!("hi number {} from the main thread!", i);
        thread::sleep(Duration::from_millis(1));
    }

    handle.join().unwrap();
}
/* Output:
hi number 1 from the main thread!
hi number 2 from the main thread!
hi number 1 from the spawned thread!
hi number 3 from the main thread!
hi number 2 from the spawned thread!
hi number 4 from the main thread!
hi number 3 from the spawned thread!
hi number 4 from the spawned thread!
hi number 5 from the spawned thread!
hi number 6 from the spawned thread!
hi number 7 from the spawned thread!
hi number 8 from the spawned thread!
hi number 9 from the spawned thread!
*/

Channels
...

I canali (channels) sono in grado di far comunicare i threads tra di loro passandosi dati.

use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let vals = vec![
            String::from("hi"),
            String::from("from"),
            String::from("the"),
            String::from("thread"),
        ];

        for val in vals {
            tx.send(val).unwrap();
            thread::sleep(Duration::from_secs(1));
        }
    });

    for received in rx {
        println!("Got: {}", received);
    }
}
/* Output:
Got: hi
Got: from
Got: the
Got: thread */

Un altro esempio più complesso può essere:

use std::sync::mpsc;  
use std::thread;  
use std::time::Duration;  
  
fn main() {  
    let (tx, rx) = mpsc::channel();  
  
    let tx1 = tx.clone();  
    thread::spawn(move || {  
        let vals = vec![  
            String::from("hi"),  
            String::from("from"),  
            String::from("the"),  
            String::from("thread"),  
        ];  
  
        for val in vals {  
            tx1.send(val).unwrap();  
            thread::sleep(Duration::from_secs(1));  
        }  
    });  
  
    thread::spawn(move || {  
        let vals = vec![  
            String::from("more"),  
            String::from("messages"),  
            String::from("for"),  
            String::from("you"),  
        ];  
  
        for val in vals {  
            tx.send(val).unwrap();  
            thread::sleep(Duration::from_secs(1));  
        }  
    });  
  
    for received in rx {  
        println!("Got: {}", received);  
    }  
}
/*
Got: hi
Got: more
Got: messages
Got: from
Got: for
Got: the
Got: you
Got: thread
*/

Mutex
...

Un mutex (Mutual Exclusion) è un meccanismo per garantire che solo un thread alla volta possa accedere a un dato condiviso.
Documentazione ufficiale di Rust sui Mutex

use std::sync::Mutex;  
  
fn main() {  
    let m = Mutex::new(5);  
  
    {  
//        let mut num = m.lock().unwrap();  
//        *num = 6;  
        *m.lock().unwrap() = 6;  
    }  
  
    println!("m = {:?}", m);  
}

Arc
...

In Rust, Arc (Atomic Reference Counting) è un tipo di dato che fornisce condivisione di proprietà di dati attraverso più thread. Questo è particolarmente utile quando si desidera condividere dati tra più thread in modo che ciascuno possa accedervi in modo sicuro e concorrente.

Arc (Atomic Reference Co unting)
...

Arc è una struttura dati che consente di condividere un valore tra più proprietari, permettendo accessi in lettura e scrittura immutabili. Il conteggio dei riferimenti viene aggiornato in modo atomico, quindi è thread-safe.

Quando si utilizza Arc, ogni volta che viene creato un nuovo proprietario del valore condiviso, il conteggio dei riferimenti aumenta di uno. Quando un proprietario viene distrutto, il conteggio dei riferimenti diminuisce di uno. Quando il conteggio dei riferimenti raggiunge zero, il valore condiviso viene deallocato.

Funzione .lock()
...

Il metodo .lock() è utilizzato in combinazione con un Mutex (Mutual Exclusion), che è una struttura dati utilizzata per fornire accesso sicuro e concorrente a un valore. Quando chiami .lock() su un Mutex, acquisisci un lock esclusivo che impedisce ad altri thread di accedere al valore fino a quando non rilasci il lock.

Quando si utilizza Arc<Mutex<T>>, puoi chiamare .lock() su di esso per ottenere un riferimento immutabile al valore protetto dal Mutex. Questo metodo restituirà un Result, che sarà Ok(mutex_guard) se il lock è stato acquisito con successo o Err se ci sono stati problemi (ad esempio, se un altro thread ha già acquisito il lock e non lo ha ancora rilasciato).

Ecco un esempio di come utilizzare Arc e .lock() insieme:

// Importiamo i tipi Arc e Mutex dal modulo std::sync
use std::sync::{Arc, Mutex};

fn main() {
	// Creiamo un valore condiviso protetto da un Mutex
    let data = Arc::new(Mutex::new(0));
    // Creiamo un vettore per immagazzinare i manici dei thread
    let mut handles = vec![];
    
    for _ in 0..10 {
	    // Cloniamo l'Arc per passarlo a ogni thread
        let data = Arc::clone(&data); 
        // Creiamo un nuovo thread
        let handle = std::thread::spawn(move || { 
            // Acquisiamo il lock su Mutex e otteniamo un riferimento immutabile al valore
            let mut num = data.lock().unwrap();
            *num += 1; // Modifichiamo il valore protetto dal Mutex
        });
        // Aggiungiamo il manico del thread al vettore
        handles.push(handle);
    }

    for handle in handles {
	    // Attendiamo che ogni thread finisca l'esecuzione
        handle.join().unwrap(); 
    }
	// Stampiamo il valore finale dopo che tutti i thread hanno finito
    println!("Valore finale: {}", *data.lock().unwrap());
}
/* Output:
Valore finale: 10 */

In questo esempio, data è un Arc contenente un Mutex che protegge un intero. Ogni thread incrementa il valore intero protetto dal Mutex tramite .lock(). Grazie all'utilizzo di Arc e Mutex, l'accesso concorrente al valore è reso sicuro e thread-safe.