Pthread mutex per thread group

2019-08-02 12:05发布

问题:

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...

Thank you.

回答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.

If alternatively you mean you want one writer thread and two ore more readers you can use rwlocks.



回答2:

yet I am to read up on posix semaphore suggested (which seems quite what I want) I've found the way of doing it in "old fashion": Stevens UNP p. 703, using pthread_cond, the metacode would be like this:

int var = 0;
pthread_mutex_t M;
pthread_cond_t C;

threadA:      lock M; var++; unlock M; do_job; lock M; var--; cond_signal(&C); unlock M
threadB:      lock M; var++; unlock M; do_job; lock M; var--; cond_signal(&C); unlock M

thread Main:  lock M; while (var > 0) cond_wait(&C, &M); do_protected_job; unlock M

Perhaps, semaphore allows same in less cumbersome way, I'll check...