Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88906

This slightly modified Rc<()> is Sync, but not Send, right?

I've searched for types that are Sync, but not Send, because it often looks like one trait is a superset of the other one (“every type that implements Sync also implements Send”). I've found this question, but the only real answer is really complicated.

So I've come up with this code:

struct Foo(Rc<()>);  // <-- private field

impl Foo {
    fn my_clone(&mut self) -> Self {  // <-- mutable borrow
        Foo(self.0.clone())
    }
}

I know that the compiler won't automatically implement Send nor Sync for my type; but I'm interested in what I could safely implement manually. I think:

Is this reasoning correct or am I missing something?

Upvotes: 6

Views: 321

Answers (1)

Matthieu M.
Matthieu M.

Reputation: 300099

I know that the compiler won't automatically implement Send nor Sync for my type.

Indeed, the compiler automatically implements Send and Sync for you, only when it can determine it is safe to do so.

This little program:

use std::cell::Cell;
use std::sync::atomic::AtomicUsize;

fn ensure_sync<T: Sync>(_: T) {}

struct Automatic(AtomicUsize);

impl Automatic {
    fn new() -> Automatic { Automatic(AtomicUsize::new(0)) }
}

fn main() {
    ensure_sync(AtomicUsize::new(0));
    ensure_sync(Automatic::new());
    ensure_sync(Cell::new(0));
}

Only errors out on the Cell::new(0) line, Automatic is Sync because all its fields are Sync.


Regarding Foo, Rc is neither Sync nor Send, so indeed the compiler will not implement either for you.

Can Foo be Sync?

I believe1 so. As long as NO other operation is added to the module that operate on immutable references. Now or in the future.

Can Foo be Send?

I agree with your conclusion, but I think you missed another method that modifies the Cell: drop.

So, indeed, you seem to have come up with a type that is Sync and not Send, by using an underlying type that is Send and not Sync. It may be my nerd sense, I find it quite amusing :)

1 When dealing with unsafe code, I am never sure of anything. It's very easy to fool oneself into thinking something is safe, simply because a tiny little detail escaped attention.

Upvotes: 4

Related Questions