Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a C++ equivalent of java.util.concurrent.locks.ReentrantReadWriteLock?

I would like to control access to getters and setters for a bunch of data classes to make them safely accessible from multiple threads simultaneously. I have done this in Java before with java.util.concurrent.locks.ReentrantReadWriteLock and it was pretty painless.

But now I'm having a lot of trouble in my current C++ project because I can't find a reentrant read/write lock implementation. Specifically, I want one that allows a thread to obtain the read lock if it already has the write lock, without blocking and without giving up the write lock first.

The reason is simple: Some of my setter methods call getter methods and the former (typically) obtain write locks and the latter read locks. I do not want to contort my straightforward getter/setter architecture just to work around limitations in lock classes.

I have tried Qt (4.8) QReadWriteLock and related classes, and Boost's unique_lock and shared_lock. Neither library implements the reentrancy I need. Does some other part of Boost address this?

Or is there some other library that has this? I'm really surprised neither Qt nor Boost seem to since it seems like such an obviously desirable feature. (And which has been part of the Java standard library since 2004.)

like image 815
Chris Avatar asked Jun 26 '13 17:06

Chris


1 Answers

As someone who has dabbled in multitreading with C++, I'm not sure you're going to find this functionality in a widely distributed library. As far as I know, boost threads, std threads, and POSIX threads don't allow for this.

As a result, in order to solve your problem I would suggest the following:

  1. Take another look at your locking scheme and the data you are sharing. Is there another way that you can accomplish what you are setting out to do?

  2. Try to implement your own version of the locking primatives you seek. It should just be a relatively simple extension of primatives already avalaible in whatever library you choose. Also, share it with the community since I'm sure you won't be the only one with this issue.

like image 149
It'sPete Avatar answered Nov 13 '22 18:11

It'sPete