Pthread mutex per thread group

我们两清 提交于 2019-12-11 07:55:52

问题


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



来源:https://stackoverflow.com/questions/18493241/pthread-mutex-per-thread-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!