使 pthread_rwlock_wrlock 递归
我对 pthread 函数 pthread_rwlock_wrlock 的行为有疑问。上面链接的规范指出,当一个线程锁定了写入锁并且同一线程再次锁定它时,它会导致未定义的行为(我实际上可以观察到这一点,因为在 x86 Linux 上调用此函数是一个 noop,而在 PowerPC Linux 上它使线程停顿)。
我需要的行为是具有以下特征的读写锁:
- 如果满足以下条件,则线程的读锁定成功:
- 该锁未被任何线程持有
- 该锁仅被零个或多个线程(包括调用线程)读锁定,并且可能被调用线程读或写锁定
- 写锁定成功:
- 该锁未被任何其他线程持有
- 只有当前线程持有锁(用于读取或写入)
使用 pthread_mutex_t,可以通过初始化标志控制锁的递归性,但这对于 pthread_rwlock_t
来说是不可能的。
我有什么选择?我实际上从未在 C 中实现过这种并发原语,而且我认为我在这里缺少一些明显的解决方案。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
老实说,递归锁定确实有一些用途,但通常它是一种黑客手段。我现在似乎找不到这篇文章,但布滕霍夫对此有一个很好的咆哮。
回到问题。您可以保留一个特定于线程的标志来表示:“我有锁”。锁定后立即设置,解锁前取消设置。由于这是访问它的唯一线程,因此您应该是安全的。因此,当尝试锁定时,您只需检查:“嘿,这个东西已经锁定了吗?”。
附带说明:如果一个线程尝试锁定两次,您确定设计没问题吗?
编辑
找到文章。
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.