Condition variable signalling issue

♀尐吖头ヾ 提交于 2019-12-11 02:43:31

问题


I am in a soup. The idea may be bad but i do need a solution.

  • I have two condition variable, say A and B.

  • Threads 1, 2 and 3 are waiting on A. Thread 4 is waiting on B.

  • B will be pthread_cond-signal() by thread 2, that is thread 4 will be signaled to wake up by thread 2.

Now, I have another thread 5 which pthread_cond_broadcasts() on condition variable A. I need all threads 1, 2 and 3 to wake up before thread 4 wakes up. That is say if thread 2 wakes up and signals on B thread 4 may wake up before thread 3 does, which is not what i want.

Any pointers will be highly appreciated.

thanks


回答1:


Use a semaphore: have each of threads 1-3 post the semaphore, and have thread 4 wait on the semaphore 3 times instead of on a condition variable.

You'll want to use sem_init(3) or sem_open(3) to create the semaphore, sem_post(3) to post the semaphore, sem_wait(3) to wait on the semaphore, and then either sem_destroy(3) (if created with sem_init) or sem_close(3) and sem_unlink(3) (if created with sem_open) to destroy the semaphore.




回答2:


You can solve this using condition variables. Instead of having Thread 4 wait just for the condition set by Thread 2, have it wait for a condition that is only set after all of Thread 1, Thread 2 and Thread 3 have done their thing:

pthread_mutex_lock(&thread4_lock);
while (!thread1_flag || !thread2_flag || !thread3_flag)
    pthread_cond_wait(&thread4_cond, &thread4_lock);
pthread_mutex_unlock(&thread4_lock);

/* Thread 4 can continue */

When Thread 1 has done its thing, it sets its part of the condition:

pthread_mutex_lock(&thread4_lock);
thread1_flag = 1;
pthread_cond_signal(&thread4_cond);
pthread_mutex_unlock(&thread4_lock);

...and likewise for Thread 2 and Thread 3. Thread 4 will only continue once all the flags have been set.




回答3:


Consider using ZeroMQ's in-process signalling for this. ZeroMQ implements a messaging model which can be used effectively to coordinate threads, as well as for inter process or network messaging.

For more info: http://api.zeromq.org/2-1-1:zmq-inproc

Here is an example of load-balancing between threads using ZeroMQ and Java.



来源:https://stackoverflow.com/questions/6935792/condition-variable-signalling-issue

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