Error while passing Arc::clone() to function in thread::spawn


#1

I’m playing with Arc’s and Mutex’s. I have a function that takes an Arc<Mutex> variable

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

fn fun(n: Arc<Mutex<u32>>)
{
	let mut n = n.lock().unwrap();
	*n += 11;
}

In the main function, if I write this

thread::spawn(|| fun(Arc::clone(&num)));

It gives me an error saying that the closure may outlive the current function and for this reason I can’t borrow the variable num. But if I do

let n = Arc::clone(&num);
thread::spawn(|| fun(n));

everything seems to be fine. I don’t understand way, since I’m “cloning” the variable in both the scenarios. Can someone explain me why it gives me that error?
Thanks!


#2

If you clone in the closure, that closure has to capture that &num reference you’re cloning from, but the error is that this reference is not 'static as thread::spawn requires.

When you clone beforehand, the closure only has to capture the resulting clone n by value.


#3

Ok, now it seems like I asked a stupid question. Thank you very much :slight_smile: