Chr*_*ski 10 multithreading rust
我认为渠道的全部目的是在线程之间共享数据.我有这个代码,基于这个例子:
let tx_thread = tx.clone();
let ctx = self;
thread::spawn(|| {
...
let result = ctx.method()
tx_thread.send((String::from(result), someOtherString)).unwrap();
})
Run Code Online (Sandbox Code Playgroud)
哪里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`
Run Code Online (Sandbox Code Playgroud)
我在哪里出错了我很困惑.除非我在错误的地方寻找并且我的问题实际上是我的用途let ctx = self;?
blu*_*uss 17
发件人不能在线程之间共享,但可以发送!
它实现了特征,Send但没有Sync(同步:安全访问Sender跨线程的共享引用).
通道的设计意味着您.clone()是发送者并将其作为值传递给线程(对于您拥有的每个线程).你move在线程的闭包上缺少关键字,它指示闭包通过获取它们的所有权来捕获变量.
如果必须在多个线程之间共享单个通道端点,则必须将其包装在互斥锁中.Mutex<Sender<T>> 是 Sync + Send where T: Send.
有趣的实施说明:该频道开始用作具有单个制作人的流.在第一次克隆发件人时,内部数据结构将升级为多生产者实现.
| 归档时间: |
|
| 查看次数: |
4866 次 |
| 最近记录: |