< 返回版块

bell 发表于 2022-05-01 09:23

rust这边定义一个单例,是一个全局静态对象如下所示: static INSTANCE: OnceCell<RwLock<HashMap<usize, recast::RecastQuery>>> = OnceCell::new();

其中 RecastQuery数据结构为 pub struct RecastQuery { q: ptr::NonNull<c_void>, } c_void 执行C分配的一块内存数据,初始化之后就不会再修改

cargo build之后报错提示: error[E0277]: NonNull<c_void> cannot be sent between threads safely --> crates\recast\src\lib.rs:82:18 | 82 | static INSTANCE: OnceCell<RwLock<HashMap<usize, recast::RecastQuery>>> = OnceCell::new(); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ NonNull<c_void> cannot be sent between theads safely

堆栈: = help: within (usize, RecastQuery), the trait Send is not implemented for NonNull<c_void> = note: required because it appears within the type RecastQuery = note: required because it appears within the type (usize, RecastQuery) = note: required because of the requirements on the impl of Send for `hashbrown::raw::RawTable<(usize, RecastQuery)

= note: required because it appears within the type hashbrown::map::HashMap<usize, RecastQuery, RandomState> = note: required because it appears within the type HashMap<usize, RecastQuery> = note: required because of the requirements on the impl of Sync for RwLock<HashMap<usize, RecastQuery>> = note: 1 redundant requirement hidden = note: required because of the requirements on the impl of Sync for once_cell::imp::OnceCell<RwLock<HashMap>> = note: required because it appears within the type once_cell::sync::OnceCell<RwLock<HashMap<usize, RecastQuery>>> = note: shared static variables must have a type that implements Sync

请问大佬如何使用全局静态对象,该全局对象存储KV结构,V中必须包含c_void,因为该指针必须指向c中的对象数据? 搞了好几天了 一直没搞定,rust的限制让人崩溃!

评论区

写评论
作者 bell 2022-05-01 21:56

感谢!!可以了,对RecastQuery 使用send 和Sync不得行,必须包一层

--
👇
Bai-Jinlin: 我这里可以呀? https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=992ae4015d7b3792cf4d2e0998ffa702

--
👇
bell: 尝试过了,提示的也是一样的

--
👇
Bai-Jinlin: 让这个通过编译很简单,仿照下面就行,但是这样出了问题就是你的事了

struct SyncPtr(NonNull<i32>);
unsafe impl Sync for SyncPtr{}
unsafe impl Send for SyncPtr{}
static CELL:OnceCell<RwLock<HashMap<i32,SyncPtr>>>=OnceCell::new()
Bai-Jinlin 2022-05-01 19:38

我这里可以呀? https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=992ae4015d7b3792cf4d2e0998ffa702

--
👇
bell: 尝试过了,提示的也是一样的

--
👇
Bai-Jinlin: 让这个通过编译很简单,仿照下面就行,但是这样出了问题就是你的事了

struct SyncPtr(NonNull<i32>);
unsafe impl Sync for SyncPtr{}
unsafe impl Send for SyncPtr{}
static CELL:OnceCell<RwLock<HashMap<i32,SyncPtr>>>=OnceCell::new()
作者 bell 2022-05-01 18:06

尝试过了,提示的也是一样的

--
👇
Bai-Jinlin: 让这个通过编译很简单,仿照下面就行,但是这样出了问题就是你的事了

struct SyncPtr(NonNull<i32>);
unsafe impl Sync for SyncPtr{}
unsafe impl Send for SyncPtr{}
static CELL:OnceCell<RwLock<HashMap<i32,SyncPtr>>>=OnceCell::new()
Bai-Jinlin 2022-05-01 11:45

让这个通过编译很简单,仿照下面就行,但是这样出了问题就是你的事了

struct SyncPtr(NonNull<i32>);
unsafe impl Sync for SyncPtr{}
unsafe impl Send for SyncPtr{}
static CELL:OnceCell<RwLock<HashMap<i32,SyncPtr>>>=OnceCell::new()
1 共 4 条评论, 1 页