首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

Boost.Interprocess 共享記憶體 HashMap 實現跨進程 Key-Value 存取

     編輯:關於C++

場景

多進程需共享 unordered_map,要求高性能、自動同步。用 Boost.Interprocess 管理共享記憶體段,配合 boost::unordered_map 及自定義分配器。

關鍵型別定義

using KeyType = int;
using MappedType = float;
using ValueType = pair;

using ShmAlloc = boost::interprocess::allocator;

using ShmHashMap = boost::unordered_map, equal_to, ShmAlloc>;

建立/開啟共享記憶體並構造 HashMap

namespace bip = boost::interprocess;

bip::managed_shared_memory segment(
    bip::open_or_create, "ContainerSharedMemory", 65536); // 64KB

ShmHashMap* map1 = segment.find_or_construct("ShmHashMap1")
    (3, boost::hash(), equal_to(), segment.get_allocator());

ShmHashMap* map2 = segment.find_or_construct("ShmHashMap2")
    (3, boost::hash(), equal_to(), segment.get_allocator());
  • find_or_construct:首次建構,後續進程直接映射同名物件。
  • 建構參數:桶數、哈希函數、相等判斷、分配器。

跨進程讀寫範例

// 進程 1
for (int i=0; i<5; ++i) {
    auto it = map1->find(i);
    if (it != map1->end()) { cout << "[1] " << i << " -> " << it->second << "\n"; it->second += 1.0f; }
    map1->insert({i, static_cast(i)});
}

// 進程 2 (同時運行)
for (int i=0; i<5; ++i) {
    auto it = map2->find(i);
    if (it != map2->end()) { cout << "[2] " << i << " -> " << it->second << "\n"; it->second += 2.0f; }
    map2->insert({i, static_cast(i)});
}

注意事項

  • 同步:unordered_map 非線程安全,多執行緒/進程並發寫入需外部鎖 (如 `bip::interprocess_mutex`)。
  • 記憶體增長:共享記憶體大小固定,超過會拋 `bad_alloc`。生產環境建議預估容量或用 `managed_mapped_file` 可擴展。
  • 清理:程式結束不自動釋放共享記憶體,需手動 `bip::shared_memory_object::remove("ContainerSharedMemory")` 或重啟 OS。
  • 型別限制:放入共享記憶體的型別必須是 TriviallyCopyable 或支援 Boost 序列化,不能包含原始指標/虛函數/STL 容器 (除非用 offset_ptr)。

完整可編譯範例

#include 
#include 
#include 
#include 
#include 
#include 

int main() {
    using namespace boost::interprocess;
    using KeyType = int; using MappedType = float;
    using ValueType = pair;
    using ShmAlloc = allocator;
    using ShmHashMap = boost::unordered_map, equal_to, ShmAlloc>;

    managed_shared_memory seg(open_or_create, "MyShmHashMap", 1<<20); // 1MB
    ShmHashMap* mp = seg.find_or_construct("Map")(100, boost::hash(), equal_to(), seg.get_allocator());

    // Demo: 寫入 1000 筆
    for(int i=0;i<1000;++i) (*mp)[i] = i * 1.5f;
    cout << "Inserted 1000, size=" << mp->size() << "\n";

    // 讀取驗證
    for(int i=0;i<10;++i) cout << i << ":" << (*mp)[i] << " ";
    cout << "\nDone.\n";
    return 0;
}

編譯命令

g++ -std=c++17 -O2 -pthread shm_hashmap.cpp -lboost_system -lrt -o shm_hashmap

Boost.Interprocess 提供零拷貝、進程隔離的高性能共享容器,是 C++ 多進程協作的利器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved