检查pthread_rwlock_t的状态 [英] Checking state of a pthread_rwlock_t

查看:117
本文介绍了检查pthread_rwlock_t的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在修改我编写的一些代码,并且遇到了这种情况:我应该写出能做以下事情的东西

Hi,
I''m revising some code i wrote and i''ve this scenario: i should write something that does the following

If a pthread_rwlock_t is not in use (i mean, no one holds it, and no one is waiting for it)
      destroy it



现在,我该怎么做检查?我的意思是,我认为pthread_rwlock_t的不同实现具有不同的结构字段(在我的系统上,pthread_rwlock_t是联合tbh,我认为该类型没有标准),所以我应该通过pthread函数来实现,但是如何?我还发现,如果您在繁忙" rwlock上调用破坏",则它不是标准行为(繁忙"是指有人拿着它或有人在等待它)
我怎样才能做到这一点?我唯一的想法是使用这样的结构



Now, how can i do this check? I mean, i think that different implementations of pthread_rwlock_t have different structure fields (on my system, pthread_rwlock_t is a union tbh, i think there isn''t a standard for the type), so i should do it through pthread functions, but how? Also i found out that "destroy" has not a standard behaviour if you call it on a "busy" rwlock (with busy, i mean that someone holds it or someone is waiting for it)

How can i do this? The only idea i have is using a struct like this

struct MyLock
{
  pthread_rwlock_t l;
  int waiting;
}



在调用rdlock或wrlock之前增加每次等待的时间,并在我每次获取该锁之前增加其等待的时间,然后我可以检查是否可以销毁它,除非且仅当我获得对它的排他锁(这意味着没有人持有它)且等待时间为零..还有其他不需要我计算等待线程数的想法吗?



increase waiting everytime before calling rdlock or wrlock and deacreasing everytime i acquire the lock, and then i could check if i can destroy it if and only if i acquire the exclusive lock on it (that means no one is holding it) and waiting is zero.. any other ideas that don''t require me to count the threads waiting?

推荐答案

即使我们假装您建议的参考计数解决方案将按预期工作(您将需要使用与 ^ ]),以避免在围绕waiting变量递增和递减的代码周围进行额外的锁定).问题是,即使您确定没有其他线程正在持有该锁,并且也没有人在等待它,您仍不能确定没有线程要抓住该锁.此外,其他线程需要在获取锁之前检查该锁是否已被破坏-此操作也需要同步.

通常,我避免动态创建和销毁锁.我在构造函数中创建所需的所有锁,然后在析构函数中销毁它们.对于需要同步的更多动态情况,我使用互锁指令来避免完全锁定.
A solution to this problem is not going to be pretty, even if we pretend that the reference counting solution that you suggested is going to work as expected (you would need to use something similar to InterlockedIncrement[^] to avoid additional locking around the code that increments and decrements the waiting variable). The problem is that even if you are certain that no other thread is holding the lock, and also that nobody is waiting on it, you cannot be sure that there are no threads that are about to grab that lock. Additionally, other threads would need to check if the lock has been destroyed before acquiring it - an operation that needs to be synchronized, too.

Generally, I avoid creating and destroying locks dynamically. I create all locks that I need in a constructor, and destroy them in the destructor. For more dynamic situations requiring synchronization I use interlocked instructions to avoid locking altogether.


这篇关于检查pthread_rwlock_t的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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