【发布时间】:2020-12-18 17:29:31
【问题描述】:
我有一个结构体,其字段为 Sender。
pub struct GenericConnectionPool<E>
where
E: ConnectionConnector,
{
_sender: Sender<()>,
_reciever: Arc<Mutex<Receiver<()>>>,
_num_of_live_connections: AtomicU8,
_max_connections: u8,
_min_connections: u8,
_connections: Arc<Mutex<Vec<<E as ConnectionConnector>::Conn>>>,
_connector: E,
}
我在多个线程中使用该结构,这就是为什么在 Arc 中使用它并克隆它的原因。
let pool = Arc::new(GenericConnectionPool::new(2, 1, cc));
println!("here");
{
for _ in 0..3 {
let pool = Arc::clone(&pool);
std::thread::spawn(move || {
pool.get_connection();
thread::sleep(Duration::from_secs(1));
});
}
}
但我收到了我的结构无法跨线程发送的错误。
`std::sync::mpsc::Sender<()>` cannot be shared between threads safely
within `GenericConnectionPool<tests::connector_works::DummyConnectionConnector>`, the trait `std::marker::Sync` is not implemented for `std::sync::mpsc::Sender<()>`
required because it appears within the type `GenericConnectionPool<tests::connector_works::DummyConnectionConnector>`
required because of the requirements on the impl of `std::marker::Send` for `std::sync::Arc<GenericConnectionPool<tests::connector_works::DummyConnectionConnector>>`
required because it appears within the type `[closure@src/lib.rs:169:36: 172:18 pool:std::sync::Arc<GenericConnectionPool<tests::connector_works::DummyConnectionConnector>>]`
我的理解是Sender类型不能安全地跨线程发送,但是由于它的cloneable,你可以克隆它然后跨线程发送。但在我的情况下,发件人在我的结构中。我想不出办法来解决这个问题。
我想我可能不得不改变我的设计。
【问题讨论】:
标签: multithreading rust