Problem solved – use Mutex

Rust provides us with Mutex<T>. This works in much the same way as other languages by locking the thread. We implement mutex in our code like this:

use std::sync::{Arc, Mutex}; 
use std::thread; 
use std::time::Duration; 
fn main()  
{ 
    let primes = Arc::new(Mutex::new(vec![1,2,3,5,7,9,13,17,19,23])); 
 
    for i in 0..10  
    { 
        let primes = primes.clone(); 
        thread::spawn(move ||  
        {  
            let mut data = primes.lock().unwrap(); 
            data[0] += i;  
        }); 
    } 
    thread::sleep(Duration::from_millis(50)); 
} 
The code for this example is in Chapter 11/mutex.

By using lock, we only allow a single thread to have access to that data at any one time (it has mutual exclusion). No other thread has access to that value, and if any other thread tries to access the value, it has to wait until the lock is released. When data goes out of scope (when i is incremented), the lock is released.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset