rust - Rust:如何使用 Arc 在新生成的线程中使用特征中定义的方法?
问题描述
所以我试图在一个特征中定义一个方法,它会产生一个线程并利用另一个特征方法,但我有点坚持如何从 Arc<...> 中“解包”它:
use std::sync::Arc;
use std::sync::Mutex;
use websocket::{Message, WebSocketResult};
trait Sender<S>
where
S: Into<Message<'static>> + Send,
{
fn send_once(&mut self, message: S) -> WebSocketResult<()>;
fn send_in_thread(&mut self, sleep_interval: time::Duration) -> WebSocketResult<()> {
let self_copy = Arc::new(Mutex::new(self)).clone();
let thread_join_handle = thread::spawn(move || self_copy.send_once(message));
thread_join_handle.join().unwrap()
}
}
我得到的错误是:
no method named `send_once` found for struct `std::sync::Arc<std::sync::Mutex<&mut Self>>` in the current scope
method not found in `std::sync::Arc<std::sync::Mutex<&mut Self>>`
这是公平的,我没有在这个包装器类型上定义这样的方法,但是我怎样才能以最短的方式摆脱这种情况呢?或者,最惯用的方式?我使用 Arc 是因为以前Self cannot be sent between threads safely
如果我不使用它,我就有了。
解决方案
您需要先锁定互斥体以获得 a MutexGuard
,然后才能对其调用方法:
let thread_join_handle = thread::spawn(move || self_copy
.lock()
.unwrap()
.send_once(message));
推荐阅读
- javascript - 承诺中的承诺
- r - 使用断点包:“数据错误:仅数据帧”
- javascript - 函数在 Firefox 中的空格键上被调用两次
- google-apps-script - 如何在谷歌应用程序脚本中获取光标位置?
- python - Colaboratory 和 Selenium:错误消息“geckodriver”可执行文件需要在 PATH 中
- r - R中两个3D点之间的距离
- unit-testing - junit mockito 对控制器和服务方法使用相同的对象
- tensorflow - Google Cloud 上的 Item to Item 推荐引擎
- python - 列表中的Python转义字符导致问题
- node-red - 红色节点未正确显示表值?