标签:c shared-memory
我想在共享内存中创建一个unordered_map.我正在使用allocator来达到目的.
编码
void *addr;
void *pool;
int shmid;
template<class T>
class MyPoolAlloc {
private:
public:
typedef size_t size_type;
typedef ptrdiff_t difference_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef T value_type;
template<class X>
struct rebind
{ typedef MyPoolAlloc<X> other; };
MyPoolAlloc() throw() {
}
MyPoolAlloc(const MyPoolAlloc&) throw() {
}
template<class X>
MyPoolAlloc(const MyPoolAlloc<X>&) throw() {
}
~MyPoolAlloc() throw() {
}
pointer address(reference __x) const { return &__x; }
const_pointer address(const_reference __x) const { return &__x; }
pointer allocate(size_type __n, const void * hint = 0) {
pointer tmp = static_cast<T*>(addr);
addr = (void*)((char*)addr + __n);
return tmp;
}
void deallocate(pointer __p, size_type __n) {
// pMyPool->Free(reinterpret_cast<void *>(__p));
}
size_type max_size() const throw() {
//return size_t(-1) / sizeof(T);
}
void construct(pointer __p, const T& __val) {
::new(__p) T(__val);
}
void destroy(pointer __p) {
//__p->~T();
}
};
typedef std::unordered_map<int, int, std::hash<int>, std::equal_to<int>, MyPoolAlloc<std::pair<const int,int>> > Map;
int main ()
{
shmid = shmget(shm_key, 1000, IPC_CREAT | IPC_EXCL | 644);
if(shmid == -1){
std::cerr << "Failed to create the shared segment." << strerror(errno)<< std::endl;
exit(-1);
}
addr = shmat(shmid, NULL, 0);
pool = addr;
if(addr == (void*)-1){
std::cerr << "Failed to attach the segment to the process." << std::endl;
shmctl(shmid, IPC_RMID, 0);
exit(-1);
}
Map *m = new(pool) Map;
m->insert(std::pair<int, int>(2,4));
shmdt(addr);
shmctl(shmid, IPC_RMID, 0);
return 0;
}
我在共享内存地址上为地图分配内存.我想对于元素,将使用allocator类的allocate()函数.但我无法弄清楚如何使用allocate函数为地图元素分配内存.
我正在尝试在地图中插入的行中获得算术异常.
有人可以帮助理解内存布局应该如何?
谢谢.
解决方法:
正如我所说的last time you asked about this,你不能将指针存储在共享内存中,并期望它们可以在多个进程中使用.和以前一样,我建议使用boost::unordered_map
in conjunction with boost::interprocess::allocator
.
如果你真的想编写自己的分配器,你需要某种自定义指针,将偏移量存储到共享内存块中,并能够从中重建正确的地址.我不建议你自己尝试这样做:除了它非常繁琐之外,你可能会发现std :: unordered_map的某些实现与非常规指针类型无法正常工作.事实上,我怀疑为共享内存制作符合标准的分配器可能是不可能的;否则,Boost分配器肯定可以被所有标准容器使用,而不仅仅是特殊的Boost版本.
顺便说一句,你不应该在自己的代码中使用像__p这样的保留名称(包含双下划线);它们只应由标准库实现使用.
标签:c,shared-memory 来源: https://codeday.me/bug/20191008/1869926.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。