Skip to content

Threads with Arc<RefCell<T>> #21469

Closed
@Munksgaard

Description

@Munksgaard

I tried doing the following

use std::thread::Thread;
use std::sync::Arc;
use std::cell::RefCell;


fn main() {
    let r = Arc::new(RefCell::new(42u8));
    let r1 = r.clone();
    let t = Thread::scoped(move || {
        loop {
            match r1.try_borrow_mut() {
                Some(n) => { *n += 1 ; break }
                _ => { }
            }
        }
    });

    t.join();
    println!("{}", *r.borrow_mut());
}

Rust complains:

$ rustc foo.rs
foo.rs:9:13: 9:27 error: the trait `core::marker::Sync` is not implemented for the type `core::cell::UnsafeCell<u8>`
foo.rs:9     let t = Thread::scoped(move || {
                     ^~~~~~~~~~~~~~
foo.rs:9:13: 9:27 error: the trait `core::marker::Sync` is not implemented for the type `core::cell::UnsafeCell<usize
>`                                                                                                                  
foo.rs:9     let t = Thread::scoped(move || {
                     ^~~~~~~~~~~~~~
error: aborting due to 2 previous errors

(Note that my code doesn't involve any UnsafeCells at all)

I was under the impression that, to get a shared mutable state, you wrapped a RefCell in an Arc. The docs even mention that "It's very common then to put a RefCell inside shared pointer types to reintroduce mutability", right after mentioning Arc as a smart shared pointer type. However, @eddyb mentioned on IRC that that might not be the case and suggested that it might be a documentation issue.

$ rustc --version
rustc 1.0.0-dev (3bf41dafc 2015-01-20 06:45:02 +0000)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions