4 ms·
Yes. It is actually fairly tricky to get a value across threads like this. The simplest I could come up with is this: struct UnsafeSync<T>(T); un
by kevincox 3y ago
Yes.
It is actually fairly tricky to get a value across threads like this. The simplest I could come up with is this:
struct UnsafeSync<T>(T);
unsafe impl<T> Sync for UnsafeSync<T> {}
fn main() {
let i = std::sync::Arc::new(UnsafeSync(std::cell::Cell::new(0)));
let thread_i = i.clone();
std::thread::spawn(move || {
thread_i.0.set(1);
});
eprintln!("i is {}", i.0.get());
}
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=5f790043616473095a1be2e405516546 https://play.rust-lang.org/?version=stable&mode=debug&editio...
- _nalply 3y agoWhy didn't you use a Mutex?
- kevincox 3y agoWhat are you thinking? I could have used a Mutex then cast the `&Mutex` to `&mut Mutex` so that I could call `.get_mut()`. But this didn't seem simpler.
- _nalply 3y agoI wanted to avoid unsafe. Because unsafe introduces conceptual complications and it seemed to be simpler to avoid that in an example.