I've just read the section of The Rust Programming Language about sharing the data between threads. The task is simple: to share a counter between multiple threads and increment it from these threads.
My C++ solution:
- create a simple variable on stack
- create mutex
- share both between threads
- do the job
The Rust solution, as suggested by the book:
use std::sync::{Mutex, Arc};
use std::thread;
fn main() {
let counter = Arc::new(Mutex::new(0));
let mut handles = vec![];
for _ in 0..10 {
let counter = Arc::clone(&counter);
let handle = thread::spawn(move || {
let mut num = counter.lock().unwrap();
*num += 1;
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
println!("Result: {}", *counter.lock().unwrap());
}
In C++ terms, it means creating a std::shared_ptr
for storing the counter. Is it really the best what can be done here to solve the task? It looks like significant overhead in comparison with the C++ solution.