gpt4 book ai didi

rust - 为什么我不能在线程之间发送 Mutex<*mut c_void>?

转载 作者:行者123 更新时间:2023-12-03 11:33:16 50 4
gpt4 key购买 nike

我需要在 Rust 线​​程之间共享从 C++ 创建的对象。我已经将它包装在一个 Mutex 结构中,所以现在在线程之间发送是安全的。但是编译器不会让我做什么。

error[E0277]: `*mut std::ffi::c_void` cannot be sent between threads safely
--> sendsync.rs:14:2
|
14 | thread::spawn(move || {
| ^^^^^^^^^^^^^ `*mut std::ffi::c_void` cannot be sent between threads safely
|
= help: within `Api`, the trait `std::marker::Send` is not implemented for `*mut std::ffi::c_void`
= note: required because it appears within the type `OpaqWrapper`
= note: required because it appears within the type `Api`
= note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Mutex<Api>`
= note: required because of the requirements on the impl of `std::marker::Send` for `std::sync::Arc<std::sync::Mutex<Api>>`
= note: required because it appears within the type `[closure@sendsync.rs:14:16: 19:3 safe_obj:std::sync::Arc<std::sync::Mutex<Api>>]`

我应该如何根据 Rust 规则实现这一点?这是代码:
use std::{
sync::{
Arc,Mutex,
},
ptr,
thread::{self},
};
pub struct OpaqWrapper {
pub obj_ptr: *mut ::std::os::raw::c_void,
}
pub struct Api(OpaqWrapper);

fn spawn_api_thread(safe_obj: Arc<Mutex<Api>>) {
thread::spawn(move || {
{
let my_api = safe_obj.lock().unwrap();
// my_api.whatever();
}
});
}

fn main() {
let api = Api(
OpaqWrapper {
obj_ptr: ptr::null_mut(),
}
);
let shared_api= Arc::new(Mutex::new(api));
for _ in 0..10 {
spawn_api_thread(shared_api.clone());
}
}

最佳答案

精简版

将某些内容传递给线程需要它是 Send

T:Send => Mutex<T>:Send+Sync =>  Arc<Mutex<T>>:Send

所以将 Api 标记为 Send 就足够了

长版

将某些内容传递给线程需要它是 Send

如果 Arc<T>SendSyncT 只会自动获取 Send (和 Sync )。源包含如下内容:
unsafe impl<T: ?Sized + Sync + Send> Send for Arc<T> {}
unsafe impl<T: ?Sized + Sync + Send> Sync for Arc<T> {}

但是, Mutex 只需要 Send 就可以同时是 SyncSend ,它的代码包含:
unsafe impl<T: ?Sized + Send> Send for Mutex<T> { }
unsafe impl<T: ?Sized + Send> Sync for Mutex<T> { }

这意味着 Arc<Mutex<Api>>Sync ,你需要 Mutex<Api>
Sync+Send 如果 ApiSend 就会发生。为此,您需要将 ApiOpaqWrapper 标记为 Send
unsafe impl Send for Api {}

请注意,您不需要将它们标记为 Sync,因为 Mutex 会自动获取。

关于rust - 为什么我不能在线程之间发送 Mutex<*mut c_void>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60292897/

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