写一个无序映射到共享内存不工作 [英] writing an unordered map to the shared memory not working

查看:193
本文介绍了写一个无序映射到共享内存不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图共享一个无序的地图(哈希图),但它最终以浮点异常在它试图插入地图中的数据的行。



有人可以帮助我理解我在哪里出错吗?

  #include< iostream> 
#include< string>
#include< unordered_map>

#include< sys / ipc.h>
#include< sys / shm.h>
int main()
{
std :: unordered_map< std :: string,double> * tmp;

key_t key = 5678;
int shmid = shmget(key,1000,IPC_CREAT | IPC_EXCL | 644);
if(shmid == -1){
std :: cerr<< 无法创建共享分段。 << std :: endl;
exit(-1);
}

void * addr = shmat(shmid,NULL,0);
if(addr ==(void *) - 1){
std :: cerr< 无法将细分受众群附加到流程。 << std :: endl;
exit(-1);
}

tmp = static_cast< std :: unordered_map< std :: string,double> *>(addr);
tmp-> insert(std :: pair< std :: string,double>(abc,1.2));

shmdt(addr);
return 0;
}

感谢。

解决方案

一般来说,你不能在进程之间共享复杂的结构。具体来说,指向一个进程的虚拟地址空间中的对象的指针在另一个进程的虚拟地址空间中不会有效,大多数容器实现将涉及指针。



您可以查看 Boost.Interprocess 库,其中包含各种容器和分配器共享;特别是其版本 unordered_map 可以放在共享内存中,只要使用它们的共享内存分配器,那么你可以简单地使用它作为 std :: unordered_map (虽然你仍然需要替换 std :: string 作为键)。


I am trying to share an unordered map(hash map) but it is ending up with the Floating point exception at the line where it tries to insert the data in the map.

Could someone please help in understanding where I am going wrong?

#include <iostream>
#include <string>
#include <unordered_map>

#include <sys/ipc.h>
#include <sys/shm.h>
int main ()
{
    std::unordered_map<std::string,double> *tmp;

    key_t key = 5678;
    int shmid = shmget(key, 1000, IPC_CREAT | IPC_EXCL | 644);
    if(shmid == -1){
        std::cerr << "Failed to create the shared segment." << std::endl;
        exit(-1);
    }

    void *addr = shmat(shmid, NULL, 0);
    if(addr == (void*)-1){
        std::cerr << "Failed to attach the segment to the process." << std::endl;
        exit(-1);
    }

    tmp = static_cast< std::unordered_map<std::string,double>* >(addr);
    tmp->insert (std::pair<std::string,double>("abc",1.2));

    shmdt(addr);
    return 0;
}

Thanks.

解决方案

In general, you can't share complex structures between processes. In particular, pointers to objects in the virtual address space of one process won't be valid in another, and most container implementations will involve pointers.

You could look at the Boost.Interprocess library which contains various containers and allocators suitable for sharing; in particular, their version of unordered_map can be placed in shared memory, as long as you use their shared memory allocator, so you might simply be able to use that as a replacement for std::unordered_map (although you'd still need a replacement for std::string as the key).

这篇关于写一个无序映射到共享内存不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆