Sharing Arc between threads?


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 || {

        ConnectionManager { state: state }


But I’m getting errors such as this one:

src/ 70:10 error: the trait `core::marker::Sync` is not implemented for the type `core::cell::UnsafeCell<bool>` [E0277]
src/     spawn(move || {
src/ 70:10 note: `core::cell::UnsafeCell<bool>` cannot be shared between threads safely
src/     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?


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.


Thanks, that helped! I still got an error:

src/ 64:39 error: use of unstable library feature 'alloc': Weak pointers may not belong in this module.
src/     let weak_state = state.downgrade();
src/ 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?


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.


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.


Cool, thank you all, very helpful :smile: