增强窗口共享内存互斥锁保持锁定状态

时间:2013-11-18 09:45:23

标签: c++ windows boost shared-memory

我使用具有条件的boost进程间共享内存进行服务器 - 客户端通信。在客户端中,我可以初始化共享内存一次,并在循环中等待消息,如下所示:

    try
{
    //open the shared memory object
    windows_shared_memory shm (open_only, "MySharedMemory", read_write);
    //map the whole shared memory in this process
    mapped_region region (shm, read_write);
    //get the address of the mapped region
    void * addr = region.get_address();
    //construct the shared structure in memory
    shared_memory_graphic_element *data = static_cast <shared_memory_graphic_element*>(addr);
    //read information until the other process marks the end
bool end_loop = false;
do {
    //lock the mutex
    scoped_lock<interprocess_mutex> lock(data->mutex);
    //get shared memory data
    if (!data->dataIn) {
        data->cond_empty.wait(lock);
    }
    if (std::strcmp(data->dataPointer, "last_message") == 0) {
        end_loop = true;
    }
    else 
    {
        //read the shared memory data and use it ...
            //notify the other process that the buffer is empty
        data->dataIn = false;
        data->cond_full.notify_one();
    }
} while (!end_loop);
}
catch (interprocess_exception &ex) 
{
  //handle exception;
}

在服务器中,我无法循环数据,因为它不是一次全部可用,所以我想只初始化一次共享内存并多次写入。 我试图将数据结构和共享内存对象声明为私有变量,如下所示:

private:
  shared_memory_graphic_element *data;
  windows_shared_memory shm;

然后用方法初始化它们:

void MyClass::initShareMem()
{
 try
 {
             shm = windows_shared_memory (open_or_create, "MySharedMemory", read_write, sizeof (shared_memory_graphic_element));


 }
 catch (interprocess_exception &ex)
 {
  printf ("interprocess_exception when creating shared memory");
      return;
 }
}

并在另一个中使用它们:

void MyClass::SendData()
{
     try
 {
    //map the whole shared memory in this process
      mapped_region region(shm, read_write);
      //get the address of the mapped region
      void * addr = region.get_address();
      //construct the shared structure in memory
      data = new (addr) shared_memory_graphic_element;  
      //write message
       scoped_lock<interprocess_mutex> lock (data->mutex);
       if (data->dataIn)        //waits until there is no data in the shared zone (goes through at first call)
       {
           data->cond_full.wait(lock);
       }
       //fill-in data fields...
       //notify the other process that there is a message
       data->cond_empty.notify_one();
       //mark message buffer as full
       data->dataIn = true;
  }
  catch (interprocess_exception &ex)
  {
      return;
  }
}

方法SendData()在循环中调用,客户端获取数据,它只运行一次。但是当我再次调用SendData时,等待data-&gt; cond_empty.wait(lock)的客户端进程不再被解锁。我再没有任何线索......有谁看到可能是什么原因?是否允许将共享内存作为类变量并像我一样初始化它?

0 个答案:

没有答案