rust - How to take ownership of T from Arc<Mutex<T>>? -


i want return value function protected mutex, cannot understand how properly. code not work:

use std::sync::{arc, mutex};  fn func() -> result<(), string> {     let result_my = arc::new(mutex::new(ok(())));     let result_his = result_my.clone();      let t = std::thread::spawn(move || {         let mut result = result_his.lock().unwrap();         *result = err("something failed".to_string());     });      t.join().expect("unable join thread");      let guard = result_my.lock().unwrap();     *guard }  fn main() {     println!("func() -> {:?}", func()); } 

playground

the compiler complains:

error[e0507]: cannot move out of borrowed content   --> src/main.rs:16:5    | 16 |     *guard    |     ^^^^^^ cannot move out of borrowed content 

in rust 1.15, can use arc::try_unwrap , mutex::into_inner:

use std::sync::{arc, mutex};  fn func() -> result<(), string> {     let result_my = arc::new(mutex::new(ok(())));     let result_thread = result_my.clone();      let t = std::thread::spawn(move || {         let mut result = result_thread.lock().unwrap();         *result = err("something failed".to_string());     });      t.join().expect("unable join threads");      let lock = arc::try_unwrap(result_my).expect("lock still has multiple owners");     lock.into_inner().expect("mutex cannot locked") }  fn main() {     println!("func() -> {:?}", func()); } 

Comments

Popular posts from this blog

java - Could not locate OpenAL library -

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

sorting - opencl Bitonic sort with 64 bits keys -