by berkut · 8y ago · 0 comments
Atomic ref-counts can actually have a surprising amount of overhead in many multithreaded scenarios, so much so that going back to raw pointers over shared pointers in C++ for some use cases of passing pointers around can provide a huge win.
let data = Arc::new(Mutex::new(Data::new()));
And if you want a mutable static global that's accessed across threads, you'll need something like: lazy_static! {
// 0 -> None
// 1 -> Circles
// 2 -> Bezier
static ref DRAW_ON_TOUCH: Arc<Mutex<u32>> = Arc::new(Mutex::new(0));
}
I love Rust but it is making easy things harder than they need to be.Also, the Arc isn't needed in lazy_static: just a mutex is enough for mutability, the sharing (which is what Arc controls) comes from being a static.
Of course. Rust is memory safe. The compiler will prevent you from sharing non-thread-safe reference counted objects between threads.
This is a significant advantage over C++, where the compiler offers no such protection and so the typical solution is just to use atomic reference counting (shared_ptr) everywhere.
Yes. It errors at compile time (`std::rc::Rc<i32>` cannot be sent between threads safely)
No, not unless the object is actually shared among multiple threads.