ScaryAardvark ScaryAardvark - 1 year ago 181
C++ Question

pthreads: reader/writer locks, upgrading read lock to write lock

I'm using read/write locks on Linux and I've found that trying to upgrade a read locked object to a write lock deadlocks.


// acquire the read lock in thread 1.
pthread_rwlock_rdlock( &lock );

// make a decision to upgrade the lock in threads 1.
pthread_rwlock_wrlock( &lock ); // this deadlocks as already hold read lock.

I've read the man page and it's quite specific.

The calling thread may deadlock if at
the time the call is made it holds the
read-write lock (whether a read or
write lock).

What is the best way to upgrade a read lock to a write lock in these circumstances.. I don't want to introduce a race on the variable I'm protecting.

Presumably I can create another mutex to encompass the releasing of the read lock and the acquiring of the write lock but then I don't really see the use of read/write locks. I might as well simply use a normal mutex.


Answer Source

What else than a dead lock do you want in the following scenario?

  • thread 1 acquire read lock
  • thread 2 acquire read lock
  • thread 1 ask to upgrade lock to write
  • thread 2 ask to upgrade lock to write

So I'd just release the read lock, acquire the write lock and check again if I've to make the update or not.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download