我创建了以下UtlSharedIPCWrapper
模板类,访问放置在进程间内存中的用户定义类型。
通常,此类使用简单类型,例如:
// construct a FaultReport - default to no faults
auto faultWrapper = managed_shm.construct<
UtlSharedIPCWrapper<uint64_t>>("FaultReport")(0);
这很好用,但我最近需要使用boost共享内存映射集合(boost::interprocess::map
)作为模板参数),如下所示:
using char_allocator = boost::interprocess::managed_shared_memory::allocator<char>::type;
using shm_string = boost::interprocess::basic_string<char, std::char_traits<char>, char_allocator>;
using KeyType = shm_string;
using ValueType = std::pair<const KeyType, shm_string>;
using ShmemAllocator = boost::interprocess::allocator<ValueType, boost::interprocess::managed_shared_memory::segment_manager>;
using SharedMemoryMap = boost::interprocess::map<shm_string, shm_string, std::less<KeyType>, ShmemAllocator>;
...
// create a new shared memory segment 2K size
managed_shared_memory managed_shm(open_only, "sharedmemname");
//Initialize the shared memory STL-compatible allocator
ShmemAllocator alloc(managed_shm.get_segment_manager());
auto pSharedNVPairs = managed_shm.find<UtlSharedIPCWrapper<
SharedMemoryMap>>("NameValuePairs").first;
我的问题是如何更改下面的模板类定义以将集合::值类型作为参数传递,而不是通过pSharedNVPairs->getSharedData()
更新临时地图并写入来单独读取整个地图作为一个操作它通过pSharedNVPairs->setSharedData(*pSharedNVPairs)
再次返回共享内存。我知道这对于不是集合的类型会有所不同,因此必须执行某些模板元编程魔术,如果等等,则必须执行选择性启用,但我想在我的类中添加一个方法。
// I don't know the correct signature here
void setSharedDataValue(const T::value_type& rSharedDataValue) {
boost::interprocess::scoped_lock<upgradable_mutex_type> lock(mMutex);
... not sure what to do here to update the collection
}
template<typename T>
struct UtlSharedIPCWrapper {
private:
using upgradable_mutex_type = boost::interprocess::interprocess_upgradable_mutex;
mutable upgradable_mutex_type mMutex;
/*volatile*/ T mSharedData;
public:
// explicit constructor used to initialize directly from existing memory
explicit UtlSharedIPCWrapper(const T& rInitialValue)
: mSharedData(rInitialValue)
{}
T getSharedData() const {
boost::interprocess::sharable_lock<upgradable_mutex_type> lock(mMutex);
return mSharedData;
}
void setSharedData(const T& rSharedData) {
boost::interprocess::scoped_lock<upgradable_mutex_type> lock(mMutex);
// update the shared data copy mapped - scoped locked used if exception thrown
// a bit like the lock guard we normally use
this->mSharedData = rSharedData;
}
};
答案 0 :(得分:1)
为什么不
// I don't know the correct signature here
void setSharedDataValue(const typename T::value_type& rSharedDataValue) {
boost::interprocess::scoped_lock<upgradable_mutex_type> lock(mMutex);
mSharedData.insert(rSharedDataValue);
}