1

Say I wanted to pass the reference to a Mutex inside new threads, would that be possible?

Example:

use std::sync::Mutex;
use std::thread;

fn main() {
    let counter = Mutex::new(0);
    let mut handles = vec![];

    for _ in 0..10 {
        let handle = thread::spawn( || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}
Nomnom
  • 4,193
  • 7
  • 27
  • 37

1 Answers1

1

You can't pass a reference into a thread, or at least a std::thread::spawn thread.

A thread needs to be able to live for 'static because for all it knows it will end up being the last thread and the borrow checker could not possibly work across thread boundaries to make sure that the Mutex you're referencing is still allocated.

Thus, Arc. It's not dropped while someone's still holding it, so there is no worry of valid borrows.

Nomnom
  • 4,193
  • 7
  • 27
  • 37