4 ms·
Modifying memory on the heap in multiple threads without a mutex, from one pointer. Why anyone would want that on purpose, I don't know.
by rthomas6 5y ago
Modifying memory on the heap in multiple threads without a mutex, from one pointer.
Why anyone would want that on purpose, I don't know.
- School-Cotton 5y agoWhat stops you from doing this in Rust?
- the_duke 5y agoThe language itself, unless you go out of your way to circumvent the protections with `unsafe`. In this particular case it's the `Sync` trait and the generell rules around sharing data.
- School-Cotton 5y ago> unless you go out of your way to circumvent the protections with `unsafe` I was specifically referring to the things you can do in `unsafe` blocks.
- rthomas6 5y agoIt was my impression that you can't do it even in unsafe because ownership rules still apply. But apparently I was wrong and there is a way to do it?
- School-Cotton 5y agoOwnership rules still apply _to references_, but not to raw pointers. This program prints "12". The only difficulty is that Rust's designers have intentionally made this pattern difficult by marking raw pointers as !Send, but you can get around that by wrapping them in a Send type. use std::{time::Duration, ops::{DerefMut, Deref}}; struct SendWrapper<T>(*mut T); impl<T> Deref for SendWrapper<T> { type Target = T; fn deref(&self) -> &Self::Target { unsafe { self.0.as_ref() }.unwrap() } } impl<T> DerefMut for SendWrapper<T> { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { self.0.as_mut() }.unwrap() } } unsafe impl<T> Send for SendWrapper<T> {} fn main() { let mut x = 10; let p1: *mut usize = &mut x; let p2: *mut usize = &mut x; let mut s1 = SendWrapper(p1); let mut s2 = SendWrapper(p2); let j1 = std::thread::spawn(move || { *s1.deref_mut() += 1; }); let j2 = std::thread::spawn(move || { std::thread::sleep(Duration::from_secs(1)); *s2.deref_mut() += 1; }); j1.join().unwrap(); j2.join().unwrap(); println!("x: {}", x); }
- perryizgr8 5y agoThere are many benefits. Here is a good video that explains: https://youtu.be/c1gO9aB9nbs https://youtu.be/c1gO9aB9nbs
- unrealhoang 5y agoRust does have UnsafeCell for gurus/experts to build such complex concurrency building blocks, pack it in a safe API for us plebs to use.