开发者

Condition variable signalling issue

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 b开发者_StackOverflow社区efore 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


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.


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜