具有递归锁的PThread RWLock死锁 [英] PThread RWLock Deadlocking with Recursive Locks

查看:151
本文介绍了具有递归锁的PThread RWLock死锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究一个小的沙盒示例,以帮助我弄清楚如何使用rwlocks.一切似乎都相当简单,但是我的示例偶尔会陷入僵局,并且不知道为什么会发生这种情况.

I've been working on a small sand-boxed example to help me figure out how to use rwlocks. Everything seems fairly straightforward, however I'm getting deadlocks in my example every once and a while and don't understand why it's happening.

我将代码示例放到pastebin上,因为它包含多行代码: http://pastebin.org /359203

I've put the code example on pastebin because it's more than a few lines of code: http://pastebin.org/359203

如果运行示例.当它最终陷入僵局时,最后三个打印语句将是以下两种情况之一:

If you run the example. When it eventually deadlocks the last three print statements will be one of two cases:

一个:

th4: request lock
th3: request lock
th4: locked

两个:

th3: request lock
th4: request lock
th3: locked

基于输出.在我看来,从第二次调用锁定功能到最终可能出现死锁,无论是读取锁定还是写入锁定.但是,由于其中一个线程具有锁定,并且同一线程称为第二个锁定功能,因此为什么会死锁?更有趣的是,在这种小情况下导致死锁的原因是什么?

Based on the output. To me it seems like there is an eventual deadlock from a second call to a locking function, whether it's to a read lock, or a write lock. But since one of the threads has the lock, and the same thread is what calls the second locking function, why is it deadlocking? Even more interesting, what is it in this small case that is causing the deadlock?

请注意,我使用的是Mac OS X,这是一个认真设计的示例.它是我正在处理的其他内容的沙盒,并且想要确保我正确地完成了这一部分.

Note that I'm on Mac OS X, and that this is a seriously contrived example. It's sand-boxed from something else I'm working on and wanted to make sure I get this part right.

推荐答案

pthread_rwlock支持递归读锁定,但递归写锁定.如果您在持有锁的同时写了锁,则表示您进入了未定义行为的领域.您的thfn3()就是这种情况.

pthread_rwlock supports recursive read locking, but not recursive write locking. If you write lock the lock while you already hold it, you have entered the realm of undefined behavior. This is the case for your thfn3().

如果将线程称为读取器"(thfn4)和写入器"(thfn3),则更清楚.情况一是:

It's clearer if you call the threads the "reader" (thfn4) and the "writer" (thfn3). Case one is then:

  • 阅读器尝试锁定
  • writer尝试锁定并阻止等待读者释放锁的
  • 阅读器被锁定
  • 读取器尝试再次锁定并阻止等待写入器获得锁定并释放锁定的

在这种情况下,读者可能无法再次锁定,因为有一个正在等待锁定的写入器,并且潜在的写入者阻止了潜在的读取器.

In this case, the reader is likely unable to lock again because there is a writer waiting on the lock, and would-be writers block would-be readers.

第二种情况是:

  • 作家试图锁定
  • 读者试图锁定并阻止等待作家完成
  • 作家被锁住
  • 作家试图再次锁定并阻止

这种情况只能通过诉诸rwlock实现的细节来解释.

This case can likely only be explained by appeal to details of the rwlock implementation.

这篇关于具有递归锁的PThread RWLock死锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆