我想在Rust程序的所有线程中共享一个evmap,一个无锁,最终一致的并发多值映射。
天真地看起来像这样:
#[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,
可以吗?
答案 0 :(得分:1)
可以[将
ReadHandle
/WriteHandle
直接放在惰性静态变量中吗?
否即可。如错误消息所示:
无法在线程之间安全地共享
std::cell::Cell<()>
您正在尝试放置一个在静态变量中的多线程上下文中使用时将失败的类型,该变量必须是线程安全的。
可以[在{懒惰的静态变量中放置
ReadHandle
/WriteHandle
)吗?
是,但您必须使用某些内容来同步访问权限,例如Mutex
或RwLock
:
#[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);
}
另见: