pthread_rwlock_destroy 个锁定的互斥量

pthread_rwlock_destroy of a locked mutex

销毁read/write锁时,Helgrind报如下错误:

pthread_rwlock_destroy of a locked mutex

抛开我正在销毁的是锁而不是互斥锁这一事实(尽管库的实现可能依赖于互斥锁),错误可能是准确的,特别是因为随后释放锁的尝试被标记为Helgrind 释放无效锁。

我知道销毁另一个线程仍持有的锁可能是错误的。 (锁通常与它们保护的资源一起被销毁,如果锁被持有,则意味着该资源仍在使用中,不应被销毁)。

现在我的问题:

Is it an error to destroy a lock that is still being held by the current thread?

是的,是的。 POSIX 说:

Results are undefined if pthread_rwlock_destroy() is called when any thread holds rwlock.

这很清楚 - "any thread" 包括当前线程。

推理是沿着这些思路进行的:要么另一个线程可以竞相使用当前线程的 pthread_rwlock_destroy() 获取锁,要么不能。如果它可以,那么程序就已经出错了,因为试图锁定一个未初始化的锁是未定义的;如果不能,则当前线程先解锁,再销毁即可。

If so, how can I prevent other threads from acquiring the lock and messing with the resource when I am about to destroy both?

上面的推理暗示了这个问题的答案——要销毁对象,包括其中的锁,您必须首先使任何其他线程都无法访问它。您可以通过从其他数据结构中删除对它的所有引用来做到这一点,这可能涉及获取和释放其他锁,但是一旦您隔离了对象本身,您就可以安全地解锁它,因为您的线程必须持有唯一剩余的引用。