Complete the code to create a new shared state using Arc.
use std::sync::[1]; let counter = [1]::new(0);
Arc is used to create a thread-safe reference-counted pointer for shared ownership.
Complete the code to lock the Mutex and get mutable access to the data.
use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0));
let mut num = counter.[1]().unwrap();The lock() method locks the Mutex and returns a guard for mutable access.
Fix the error in the code to share a counter safely between threads.
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(0));
let counter2 = [1].clone();
thread::spawn(move || {
let mut num = counter2.lock().unwrap();
*num += 1;
});You need to clone the original Arc pointer counter to share ownership with the thread.
Fill both blanks to create a thread-safe shared counter and increment it.
use std::sync::[1]; use std::thread; let counter = [1]::new([2]::new(0)); let counter2 = counter.clone();
Arc is used for shared ownership and Mutex for safe mutable access.
Fill all three blanks to safely share and update a counter in multiple threads.
use std::sync::[1]; use std::thread; let counter = [1]::new([2]::new(0)); let handles: Vec<_> = (0..5).map(|_| { let counter = counter.clone(); thread::spawn(move || { let mut num = counter.[3]().unwrap(); *num += 1; }) }).collect();
Arc is for shared ownership, Mutex for safe mutable access, and lock() to access the Mutex data.