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
Solution by OP.
The answer, as stated in the question comments is to use the member function
unlock_upgradable_and_lock
. If there is anboost::interprocess
analog toupgrade_to_unique_lock
, I don't know where it is. But thewriter()
function can be rewritten as: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.