Sharing Arc between threads?


#1

Hi all, I’m trying to create an object that shall be accessed by user of the object and a few threads. Something like this:

pub struct ConnectionManager {
    state: Arc<State>,
}

impl ConnectionManager {
    pub fn new(event_pipe: IoReceiver<Event>) -> ConnectionManager {
        let state = Arc::new(State{ event_pipe: event_pipe });

        let weak_state = state.downgrade();

        spawn(move || {
            start_accepting_connections(weak_state);
        });

        ConnectionManager { state: state }
    }

    ....
}

But I’m getting errors such as this one:

src/connection_manager.rs:70:5: 70:10 error: the trait `core::marker::Sync` is not implemented for the type `core::cell::UnsafeCell<bool>` [E0277]
src/connection_manager.rs:70     spawn(move || {
                                 ^~~~~
src/connection_manager.rs:70:5: 70:10 note: `core::cell::UnsafeCell<bool>` cannot be shared between threads safely
src/connection_manager.rs:70     spawn(move || {
                                 ^~~~~

I also tried to pass the Weak pointer to the thread through a mpsc channel, but that gave me a very similar error. Am I missing some idiomatic way of doing this kind of thing in Rust?


#2

Arc just shares threadsafe stuff and State in not declared threadsafe here. Put it in a mutex for threadsafe access.
For sending objects through a channel the type has to implement Send.


#3

Thanks, that helped! I still got an error:

src/connection_manager.rs:64:28: 64:39 error: use of unstable library feature 'alloc': Weak pointers may not belong in this module.
src/connection_manager.rs:64     let weak_state = state.downgrade();
                                                        ^~~~~~~~~~~
src/connection_manager.rs:64:39: 64:39 help: add #![feature(alloc)] to the crate attributes to enable

But adding the #![feature(alloc)] attribute to the crate got rid of it. I’m very new to Rust (4 days to be exact), is this an acceptable solution?


#4

Yes. The feature gates are there just to make it clear that you’re opting into unstable functionality. If you’re on a stable compiler (which isn’t a thing yet), then you will be blocked from using it.


#5

Yes, if you use unstable features, you have to declare them. This means
that your code will only run on nightly Rust for now, not the stable
versions. When we stabilize Weak, then your code will be stable too.


#6

Cool, thank you all, very helpful :smile: