Sharing a struct with trait objects as properties across threads

后端 未结 1 1774
情书的邮戳
情书的邮戳 2020-11-30 14:48

I have the code below. With the commented out parts, it\'s working. When I uncomment the parts it does not compile anymore.

How can I adjust the commented parts to m

1条回答
  •  死守一世寂寞
    2020-11-30 15:28

    I find the error message pretty straightforward:

    • the trait std::marker::Send is not implemented for Expr + 'static
    • required because of the requirements on the impl of std::marker::Send for std::sync::Arc
    • required because it appears within the type Container
    • required because of the requirements on the impl of std::marker::Send for std::sync::Arc
    • required because it appears within the type [closure@src/main.rs:64:33: 67:6 container1:std::sync::Arc]
    • required by std::thread::spawn

    You are trying to move your Arc to another thread, but it contains an Arc, which cannot be guaranteed to be safely sent (Send) or shared (Sync) across threads.

    Either add Send and Sync as supertraits to Expr:

    pub trait Expr: Send + Sync { /* ... */ }
    

    Or add them as trait bounds to your trait objects:

    pub struct AddExpr {
        expr1: Box,
        expr2: Box,
    }
    
    impl AddExpr {
        pub fn new(expr1: Box, expr2: Box) -> Self {
            Self { expr1, expr2 }
        }
    }
    
    struct Container {
        x: i32,
        cached_expr: Arc,
    }
    

    See also:

    • How can I share references across threads?
    • Multithreaded application fails to compile with error-chain
    • Is there any way to implement the Send trait for ZipFile?
    • How do I share a generic struct between threads using Arc>>?

    0 讨论(0)
提交回复
热议问题