Is there an 'upgrade_to_unique_lock' for boost::interprocess?

守給你的承諾、 提交于 2019-12-07 10:39:07

问题


I am looking for the best way to effectively share chunks of data between two (or more) processes in a writer-biased reader/writer model.

My current tests are with boost::interprocess. I have created some managed_shared_memory and am attempting to lock access to the data chunk by using an interprocess mutex stored in the shared memory.

However, even when using sharable_lock on the reader and upgradable_lock on the writer, the client will read fragmented values during write operations instead of blocking. While doing a similar reader/writer setup between threads in a single process, I used upgrade_to_unique_lock to solve this issue. However, I have not found its boost::interprocess equivalent. Does one exist?

Server (writer):

while (1) {
  // Get upgrade lock on the mutex
  upgradable_lock <MutexType> lock(myMutex);

  // Need 'upgrade_to_unique_lock' here so shared readers will block until
  // write operation is finished.

  // Write values here
}

Client (reader)

while (1)
{
  // Get shared access
  sharable_lock <MutexType> lock(myMutex);

  // Read p1's data here -- occasionally invalid!
}

I guess the bigger question at hand is this: is an interprocess mutex even the proper way to access shared memory between processes in a writer-biased setup?

Note: using Boost 1.44.0


回答1:


All Boost.Interprocess upgradable locks support upgrade per this. Definition here.

Regarding your broader question - I would think that this is precisely what you want. Readers can still work concurrently, and you have to prevent concurrent writes. Unless you can partition the shared memory such that more constrained access is guaranteed, this looks the best.




回答2:


Solution by OP.

The answer, as stated in the question comments is to use the member function unlock_upgradable_and_lock. If there is an boost::interprocess analog to upgrade_to_unique_lock, I don't know where it is. But the writer() function can be rewritten as:

while (1) {
  // Get upgrade lock on the mutex
  myMutex.lock_upgradable();

  // Get exclusive access and block everyone else
  myMutex.unlock_upgradable_and_lock();

  // Write values here

  // Unlock the mutex (and stop blocking readers)
  myMutex.unlock();
}


来源:https://stackoverflow.com/questions/4157491/is-there-an-upgrade-to-unique-lock-for-boostinterprocess

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!