Unable to move data from Mutex
Consider the following code example, I have a vector JoinHandlers
that I need it in, iterating to attach to the main thread, however I get an error when doing so error: cannot move out of borrowed content
.
let threads = Arc::new(Mutex::new(Vec::new()));
for _x in 0..100 {
let handle = thread::spawn(move || {
//do some work
}
threads.lock().unwrap().push((handle));
}
for t in threads.lock().unwrap().iter() {
t.join();
}
source to share
Unfortunately, you cannot do this directly. When it Mutex
consumes the data structure that you supplied it with, you cannot return it back by value again. You can only get a link &mut
that will prevent you from leaving it. So that into_iter()
won't even work - it needs an argument self
that it can't get from MutexGuard
.
However, there is a workaround. You can use Arc<Mutex<Option<Vec<_>>>>
instead Arc<Mutex<Vec<_>>>
, and then just the take()
value from the mutex:
for t in threads.lock().unwrap().take().unwrap().into_iter() {
}
into_iter()
Will then work fine as the value is moved to the calling thread.
Of course, you will need to plot the vector and click on it appropriately:
let threads = Arc::new(Mutex::new(Some(Vec::new())));
...
threads.lock().unwrap().as_mut().unwrap().push(handle);
However, it is best to simply delete the layer Arc<Mutex<..>>
(unless of course that value is being used from other threads).
source to share