How can I guarantee that a type that doesn't implement Sync can actually be safely shared between threads?

青春壹個敷衍的年華 提交于 2019-11-27 16:08:33

Well, one way would be to use a wrapper with an unsafe impl Sync:

extern crate crossbeam;

use std::cell::RefCell;

fn main() {
    struct Wrap(RefCell<i32>);
    unsafe impl Sync for Wrap {};
    let val = Wrap(RefCell::new(1));

    crossbeam::scope(|scope| {
        scope.spawn(|| *val.0.borrow());
    });
}

So, as usual with unsafe, it is now up to you to guarantee that the inner RefCell is indeed never accessed from multiple threads simultaneously. As far as I understand, this should be enough for it not to cause a data race.

Another solution is to move a mutable reference to the item into the thread, even though mutability isn't required. Since there can be only one mutable reference, the compiler knows that it's safe to be used in another thread.

extern crate crossbeam;

use std::cell::RefCell;

fn main() {
    let mut val = RefCell::new(1);    
    let val2 = &mut val;

    crossbeam::scope(|scope| {
        scope.spawn(move || *val2.borrow());
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!