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

谁说我不能喝 提交于 2019-11-26 17:25:33

问题


I have code that creates a RefCell and then wants to pass a reference to that RefCell to a single thread:

extern crate crossbeam;

use std::cell::RefCell;

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

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

In the complete code, I'm using a type that has a RefCell embedded in it (a typed_arena::Arena). I'm using crossbeam to ensure that the thread does not outlive the reference it takes.

This produces the error:

error: the trait bound `std::cell::RefCell<i32>: std::marker::Sync` is not satisfied [E0277]

    scope.spawn(|| *val.borrow());
          ^~~~~

I believe I understand why this error happens: RefCell is not designed to be called concurrently from multiple threads, and since it uses internal mutability, the normal mechanism of requiring a single mutable borrow won't prevent multiple concurrent actions. This is even documented on Sync:

Types that are not Sync are those that have "interior mutability" in a non-thread-safe way, such as Cell and RefCell in std::cell.

This is all well and good, but in this case, I know that only one thread is able to access the RefCell. How can I affirm to the compiler that I understand what I am doing and I ensure this is the case? Of course, if my reasoning that this is actually safe is incorrect, I'd be more than happy to be told why.


回答1:


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.




回答2:


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());
    });
}


来源:https://stackoverflow.com/questions/36649865/how-can-i-guarantee-that-a-type-that-doesnt-implement-sync-can-actually-be-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!