使用boost :: interprocess :: mutex来同步共享内存访问

时间:2016-02-02 09:41:08

标签: c++ boost shared-memory interprocess boost-mutex

我在C++开发了两个不同的应用程序。这些应用程序通过boost::interprocess::shared_memory_object相互通信。现在我需要一个mutex变量来同步两者之间的操作。有人可以为此提供一个最小的例子。我的申请代码如下:

App A:

    boost::interprocess::shared_memory_object shm (boost::interprocess::create_only, "MySharedMemory", boost::interprocess::read_write);
    shm.truncate (1024);
    boost::interprocess::mapped_region region(shm,boost::interprocess::read_write);

   std::strcpy(static_cast<char* >(region.get_address()), "WRITE\n");

/*I need to write some data to shared memory here. But line by line.     i.e., I write first line. App B reads it. Then I write second line. For this i require mutex*/

App B:

    boost::interprocess::shared_memory_object shm (boost::interprocess::open_only, "MySharedMemory", boost::interprocess::read_write);
    boost::interprocess::mapped_region region (shm, boost::interprocess::read_write);

    char *str1 = static_cast<char*> (region.get_address());
    char subbuff[5];
    memcpy( subbuff, str1, 5 );
    subbuff[5] = '\0';
    while(strcmp(subbuff,"WRITE")!=0)
    {
        str1 = static_cast<char*> (region.get_address());
        memcpy( subbuff, str1, 5 );
        subbuff[5] = '\0';
    }

/*Here I want  to read the data written by App A line by line*/

0 个答案:

没有答案