1 个不稳定版本
0.1.0 | 2023年12月20日 |
---|
#54 in #共享内存
32KB
627 行代码(不包括注释)
共享资源IPC
跨进程共享资源的包装器。
支持的操作系统
- Linux
- MacOS
- Windows
Linux/MacOS支持是通过POSIX共享内存和信号量实现的。
希望支持Windows,但近期内没有计划。
使用方法
在你的Cargo.toml
文件中,添加以下行
shared-resource-ipc = "0.1"
以下是使用此包的基本示例。
use shared_resource_ipc::SharedResource;
use serde::{Serialize, Deserialize};
#[derive(Clone, Default, Serialize, Deserialize, Default)]
struct DemoStruct {
number: usize,
name: String,
}
fn main() {
let default_value: DemoStruct = DemoStruct::default();
// Open a shared resource using a unique identifier and a default value. If this process
// is not the first to initialize the resource, the default value is ignored.
let shared_resource: SharedResource<DemoStruct> =
SharedResource::new("unique_name", default_value)
.expect("failed to open shared resource");
// Access the stored value using a clojure.
let _result = shared_resource.access(|data: &DemoStruct| {
// read the data here...
let value = data.clone();
// a value can be returned from the clojure
return value;
}).expect("failed to access shared resource");
// The value can be accessed mutably as well.
let _result = shared_resource.access(|data| {
(*data).number = 42;
}).expect("failed to mutably access shared resource");
// No cleaning is required: it is handled when the resource is dropped.
}
可能的问题
此共享资源实现不知道连接到内存段有多少个进程。
这意味着有时,一个进程会在另一个进程有机会访问之前创建、打开并完全销毁内存。在这种情况下,程序会大部分时间恐慌。然而,如果第二个进程重新创建了内存而不知道它已经被销毁,程序就不会恐慌。对于那个第二个进程来说,它被认为是第一个创建资源的,所以它不会恐慌。
解决方案:确保你的资源有一个要完成的特定目标。这样,可以测试一个条件,然后在进程中丢弃资源。
或者,可以在资源丢弃之前添加延迟,但这将降低其可预测性。
如果你知道任何解决此问题的方法,请提出一个问题。
依赖关系
~2–3MB
~61K SLoC