每个线程组的Pthread互斥锁 [英] Pthread mutex per thread group
问题描述
我正在寻找正确的解决方案来保护线程组,就像通常使用单个线程那样,即:线程1和2之一或两者都可以同时锁定互斥锁M,而1和2都不放在睡觉.互斥锁M抵靠线程3.因此,如果线程3在互斥锁被线程1或2或两者同时锁定时锁定了互斥锁,则线程3进入休眠状态.如果线程1或2在被线程3锁定时锁定了互斥锁,则1或2(以锁定状态为准)也将进入睡眠状态,直到3释放它为止.
I am looking for the right solution to protect thread group as I normally would do with a single thread, that is: threads 1 and 2 either or both can lock mutex M at the same time, neither 1 nor 2 be put to sleep. Mutex M stands against thread 3. Thus, if thread 3 locks the mutex while it's locked by either thread 1 or 2 or both, then thread 3 IS put to sleep. If thread 1 or 2 locks the mutex while it's locked by thread 3, then 1 or 2 (whichever locking it) also put to sleep until 3 releases it...
谢谢.
推荐答案
如果您的意思是在一个关键部分中希望不超过两个线程,而第三个线程不在该关键部分中,则必须使用POSiX信号量初始化为2. 信号量计数器可以初始化为任何值,每个sem_wait递减计数器(锁定它),每个sem_post递增计数器(释放它). 互斥体是初始化为1的信号量的特例.
if you mean that you want never more that two threads in a critical section, while a third thread is kept out of the critical section then you must use a POSiX Semaphore initialized to 2. Semaphore counter can be initialized to any value , every sem_wait decrement the counter (lock it) , every sem_post increment it (release it) . Mutex are special case of semaphores initiliazed to 1.
或者,如果您想要一个写入线程和两个或更多读取器,则可以使用rwlocks.
If alternatively you mean you want one writer thread and two ore more readers you can use rwlocks.
这篇关于每个线程组的Pthread互斥锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!