I have a problem regarding the behaviour of the pthread function pthread_rwlock_wrlock. The specification linked above states that when one thread has locked the lock for writing and the same thread locks it again, it results in undefined behaviour (I could actually observe this in that on x86 Linux calling this function is a noop and on PowerPC Linux it stalls the thread).
The behaviour I need would be a read write lock that has the following characteristics:
- read-locking by a thread succeeds if:
- the lock is not held by any thread
- the lock is only read-locked by zero or more threads (including the calling thread) and possibly read- or write locked by the calling thread
- write-locking succeeds when:
- the lock is not held by any other thread
- only the current thread is holding the lock (for reading or writing)
With a pthread_mutex_t
, the recursiveness of the lock can be controlled via an initialization flag, but this is not possible for pthread_rwlock_t
.
What are my options? I've never actually had to implement this kind of concurrency primitive in C, and I think I'm missing some obvious solution here.
To be honest, recursive locking does have some uses but generally it's a hack. I can't seem to find the article right now, but Butenhof has a nice rant on this.
Back to the question. You could keep a thread-specific flag that signals: "I have the lock". Set it right after locking and unset it before unlocking. Since this is the only thread accessing it, you should be safe. So when trying to lock you simply need to check: "Hey, is this thing locked already?".
As a side note: are you sure the design is okay if a thread tries to lock twice ?
EDIT
Found the article.
But if that's all that's necessary, why does POSIX have recursive mutexes?
Because of a dare.
来源:https://stackoverflow.com/questions/7125250/making-pthread-rwlock-wrlock-recursive