gpt4 book ai didi

multithreading - Rust mpsc::Sender 不能在线程间共享?

转载 作者:行者123 更新时间:2023-11-29 07:43:32 29 4
gpt4 key购买 nike

我认为 channel 的全部目的是在线程之间共享数据。我有这个代码,based on this example :

let tx_thread = tx.clone();
let ctx = self;
thread::spawn(|| {
...
let result = ctx.method()
tx_thread.send((String::from(result), someOtherString)).unwrap();
})

在哪里txmpsc::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; 的使用?

最佳答案

Sender 不能在线程之间共享,但可以发送!

它实现了特征 Send但不是 Sync (同步:跨线程访问对 Sender 的共享引用是安全的)。

channel 的设计是为了你.clone()发件人并将其作为值传递给线程(对于您拥有的每个线程)。您缺少 move线程闭包上的关键字,它指示闭包通过获取变量的所有权来捕获变量。

如果您必须在多个线程之间共享单个 channel 端点,则必须将其包装在互斥体中。 Mutex<Sender<T>> Sync + Send where T: Send .

有趣的实现说明: channel 开始用作流,其中它只有一个生产者。第一次克隆发送者时,内部数据结构升级为多生产者实现。

关于multithreading - Rust mpsc::Sender 不能在线程间共享?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40384274/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com