Sync, arc, and oncecell

pub trait T: Sync {}

pub struct Foo {
    inner: Arc<dyn T>,

static instance: OnceCell<Foo> = OnceCell::new();

Rustc complains that:

OnceCell<Foo> does not implement Sync as Foo does not implement Sync.

However, since T: Sync , I expect inner: Arc<dyn T> to impl Sync, and thus Foo to auto impl Sync.

  1. What am I getting wrong ?

  2. How do I fix this ?

OnceCell doesn't protect against concurrent initialization by multiple threads.

For a thread-safe version of this struct, see std::sync::OnceLock.

1 Like

Arc<T>: Sync requires T: Send + Sync


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.