One common challenge in concurrency is managing shared state across multiple threads. Rust's ownership model, along with types like Mutex and Arc (atomic reference counting), makes this task safe and efficient.
In this challenge, you will implement a generic shared state system and use it to create thread-safe counters and other shared data structures.
Implement three functions that demonstrate different aspects of shared state concurrency:
create_shared_data: Creates shared state with any type Tincrement_counter: Demonstrates multiple threads modifying shared statemodify_shared_data: Generic function for thread-safe modificationsThe create_shared_data function should:
TMutex and ArcThe increment_counter function should:
Arc<Mutex<i32>>The modify_shared_data function should:
unwrap() to simplify the codemain function to see how the functions are usedArc::new(Mutex::new(initial)) to create thread-safe containersArc when passing it to a new thread. e.g. let cloned = Arc::clone(&shared_data)lock().unwrap() to access the data inside the MutexSend trait and have a lifetime that outlives the thread 'static