gpt4 book ai didi

concurrency - 我可以在 `evmap` 中使用 `lazy_static` 吗?

转载 作者:行者123 更新时间:2023-11-29 08:18:35 24 4
gpt4 key购买 nike

我想分享一个 evmap ,一个无锁的、最终一致的、并发的多值映射,跨 Rust 程序中的所有线程。

天真地,它看起来像这样:

#[macro_use]
extern crate lazy_static;

extern crate evmap;

use std::collections::hash_map::RandomState;

lazy_static! {
static ref MAP: (evmap::ReadHandle<u32, u32, (), RandomState>,
evmap::WriteHandle<u32, u32, (), RandomState>) = evmap::new();
}

fn main() {
println!("Hello, world!");
MAP.1.clear();
}

这给出:

error[E0277]: the trait bound `std::cell::Cell<()>: std::marker::Sync` is not satisfied in `(evmap::ReadHandle<u32, u32>, evmap::WriteHandle<u32, u32>)`
--> src/main.rs:8:1
|
8 | / lazy_static! {
9 | | static ref MAP: (evmap::ReadHandle<u32, u32, (), RandomState>,
10 | | evmap::WriteHandle<u32, u32, (), RandomState>) = evmap::new();
11 | | }
| |_^ `std::cell::Cell<()>` cannot be shared between threads safely
|
= help: within `(evmap::ReadHandle<u32, u32>, evmap::WriteHandle<u32, u32>)`, the trait `std::marker::Sync` is not implemented for `std::cell::Cell<()>`
= note: required because it appears within the type `std::marker::PhantomData<std::cell::Cell<()>>`
= note: required because it appears within the type `evmap::ReadHandle<u32, u32>`
= note: required because it appears within the type `(evmap::ReadHandle<u32, u32>, evmap::WriteHandle<u32, u32>)`
= note: required by `lazy_static::lazy::Lazy`
= note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

我认为这是在提示 evmap::new() 中返回的 ():

pub fn new<K, V>(
) -> (ReadHandle<K, V, (), RandomState>, WriteHandle<K, V, (), RandomState>) where
K: Eq + Hash + Clone,
V: Eq + ShallowCopy,

可以吗?

最佳答案

Can [placing a ReadHandle / WriteHandle directly in a lazy static variable] be done?

。如错误消息所述:

std::cell::Cell<()> cannot be shared between threads safely

您正试图将在多线程上下文中使用时会失败的类型放置在静态变量中,该变量必须是线程安全的。

Can [placing a ReadHandle / WriteHandle in a lazy static variable at all] be done?

,但您必须使用一些东西来同步访问,例如 MutexRwLock :

#[macro_use]
extern crate lazy_static;

extern crate evmap;

use std::collections::hash_map::RandomState;
use std::sync::Mutex;

type ReadHandle = evmap::ReadHandle<u32, u32, (), RandomState>;
type WriteHandle = evmap::WriteHandle<u32, u32, (), RandomState>;

lazy_static! {
static ref MAP: (Mutex<ReadHandle>, Mutex<WriteHandle>) = {
let (r, w) = evmap::new();
(Mutex::new(r), Mutex::new(w))
};
}

fn main() {
MAP.1.lock().unwrap().clear(1);
}

另见:

关于concurrency - 我可以在 `evmap` 中使用 `lazy_static` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47818811/

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