我认为通道的全部目的是在线程之间共享数据。我有基于以下示例的代码:
let tx_thread = tx.clone();
let ctx = self;
thread::spawn(|| {
...
let result = ctx.method()
tx_thread.send((String::from(result), someOtherString)).unwrap();
})
哪里tx
是mpsc::Sender<(String, String)>
error[E0277]: the trait bound `std::sync::mpsc::Sender<(std::string::String, std::string::String)>: std::marker::Sync` is not satisfied
--> src/my_module/my_file.rs:137:9
|
137 | thread::spawn(|| {
| ^^^^^^^^^^^^^
|
= note: `std::sync::mpsc::Sender<(std::string::String, std::string::String)>` cannot be shared between threads safely
= note: required because of the requirements on the impl of `std::marker::Send` for `&std::sync::mpsc::Sender<(std::string::String, std::string::String)>`
= note: required because it appears within the type `[closure@src/my_module/my_file.rs:137:23: 153:10 res:&&str, ctx:&&my_module::my_submodule::Reader, tx_thread:&std::sync::mpsc::Sender<(std::string::String, std::string::String)>]`
= note: required by `std::thread::spawn`
我对哪里出错了感到困惑。除非我在错误的地方寻找,否则我的问题实际上是我对的使用let ctx = self;
吗?
发送方不能在线程之间共享,但是可以发送!
它实现了特征,Send
但没有实现Sync
(同步:可以安全地访问Sender
跨线程的共享引用)。
通道的设计旨在使您.clone()
成为发送方,并将其作为值传递给线程(对于您拥有的每个线程)。您move
在线程的闭包上缺少关键字,该关键字指示闭包通过获取变量的所有权来捕获变量。
如果必须在多个线程之间共享单个通道终结点,则必须将其包装在互斥体中。Mutex<Sender<T>>
是 Sync + Send where T: Send
。
有趣的实现注意事项:该通道开始用作具有单个生产者的流。首次克隆发件人时,内部数据结构将升级为多生产者实现。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句