Complete the code to declare a thread-safe shared variable using Rust's atomic type.
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
let counter = AtomicUsize::new([1]);The AtomicUsize::new function requires an initial usize value. Using 0 initializes the counter correctly.
Complete the code to spawn a thread that safely increments the atomic counter.
use std::sync::Arc; use std::thread; let counter = Arc::new(AtomicUsize::new(0)); let counter_clone = Arc::clone(&counter); let handle = thread::spawn(move || { counter_clone.[1](1, Ordering::SeqCst); });
The fetch_add method atomically adds to the current value, which is safe for concurrent increments.
Fix the error in the code to safely share a mutable vector across threads using a Mutex.
use std::sync::{Arc, Mutex};
use std::thread;
let data = Arc::new(Mutex::new(vec![1, 2, 3]));
let data_clone = Arc::clone(&data);
let handle = thread::spawn(move || {
let mut vec = data_clone.[1]().unwrap();
vec.push(4);
});The lock() method acquires the mutex, allowing safe mutable access to the vector.
Fill both blanks to create a thread-safe counter using Arc and Mutex.
use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new([1]));
let counter_clone = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter_clone.[2]().unwrap();
*num += 1;
});Initialize the counter with 0 and use lock() to safely access and modify the value inside the Mutex.
Fill all three blanks to create a thread-safe HashMap shared across threads with Arc and Mutex.
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
let map = Arc::new(Mutex::new(HashMap::new()));
let map_clone = Arc::clone(&map);
let handle = thread::spawn(move || {
let mut data = map_clone.[1]().unwrap();
data.insert([2], [3]);
});Use lock() to access the Mutex-protected HashMap, then insert a key-value pair with key "key" and value 42.