Accessing Option from Mutex


#1

Hi,

I am still new to Rust.

In the following example, I am wrapping an Option in an Arc/Mutex, then I am expecting the lock().unwrap() to grant me access to my option again so I can reference my initial integer. For some reason, I can’t access the option element. I also tried to use MutexGuard’s deref() without success.

How do can I reference my initial integer after wrapping it in an option and an arc/mutex?

Thanks.

use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Deref;

fn main() {

	println!("Hello!");

	let n:i32 = 5;

	let arc = Arc::new(Mutex::new(Some(n)));

	let arc_clone = arc.clone();

	let ref_n: &i32 = match arc_clone.lock().unwrap() {

		Some(ref x) => x,
		None => panic!("Error."),
	};

	println!("{:?}", ref_n);

}

#2

Accessing it with .lock().unwrap() is correct, but the value you get from this is a “MutexGuard” that you should use as it is.

You only have access to the mutex-protected value while mutex guard is alive. You’re trying to get a reference to the value inside, while discarding the guard — that’s not possible.

For example, put the guard in a variable. let mut value = arc_clone.lock().unwrap();.


#3

Thank you bluss.

Unfortunately, I still can’t figure out how to access my option and its value from the MutexGuard, after having extended its lifetime as you rightly pointed out.

Eventually, I need to get a reference to my wrapped integer. How is this possible?

Thanks.

use std::sync::Arc;
use std::sync::Mutex;
use std::ops::Deref;

fn main() {

	println!("Hello!");

	let n:i32 = 5;

	let arc = Arc::new(Mutex::new(Some(n)));

	let arc_clone = arc.clone();

	let mut mutex_guard = arc_clone.lock().unwrap();

	let ref_n: &i32 = match mutex_guard {

		Some(ref x) => x,
		None => panic!("Error."),
	};

	println!("{:?}", ref_n);

}

#4

As written, you’re matching against the MutexGuard itself. What you want is to match against the deref target of the guard, like so:

	let ref_n: &i32 = match *mutex_guard {
		Some(ref x) => x,
		None => panic!("Error."),
	};

#5

Thank you very much!