多進程需共享 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>;
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`)。#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++ 多進程協作的利器。