首先需要在项目依赖Cargo.toml添加lazy_static依赖项
[dependencies]
lazy_static = "1.4.0"
示例代码如下:
use lazy_static::lazy_static;
use std::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread;
#[derive(Debug)]
struct SharedData {
data: Vec<u8>,
}
lazy_static! {
static ref GLOBAL_DATA: RwLock<SharedData> = RwLock::new(SharedData { data: Vec::new() });
}
fn get_write_shared_data() -> RwLockWriteGuard<'static, SharedData> {
GLOBAL_DATA.write().unwrap()
}
fn get_read_shared_data() -> RwLockReadGuard<'static, SharedData> {
GLOBAL_DATA.read().unwrap()
}
fn main() {
// 读取最初的数据
thread::spawn(|| {
let shared_data = get_read_shared_data();
println!("{:?}", shared_data);
})
.join()
.unwrap();
// 添加一个元素
thread::spawn(|| {
let mut shared_data = get_write_shared_data();
shared_data.data.push(42);
})
.join()
.unwrap();
// 读取修改后的数据
thread::spawn(|| {
let shared_data = get_read_shared_data();
println!("{:?}", shared_data);
})
.join()
.unwrap();
// 移除一个元素
thread::spawn(|| {
let mut shared_data = get_write_shared_data();
shared_data.data.retain(|&x| x != 42);
})
.join()
.unwrap();
// 读取修改后的数据
thread::spawn(|| {
let shared_data = get_read_shared_data();
println!("{:?}", shared_data);
})
.join()
.unwrap();
}
标签:lazy,示例,get,unwrap,static,shared,多线程,data From: https://www.cnblogs.com/ALXPS/p/17986792