条件变量信号问题
我在汤里。这个想法可能很糟糕,但我确实需要一个解决方案。
我有两个条件变量,比如 A 和 B。
线程 1、2 和 3 正在等待 A。线程 4 正在等待 B。
B 将由线程 2 执行 pthread_cond-signal(),即线程 4 将执行 线程2发出信号唤醒。
现在,我有另一个线程 5,它对条件变量 A 进行 pthread_cond_broadcasts()。我需要在线程 4 唤醒之前唤醒所有线程 1、2 和 3。也就是说,如果线程 2 醒来并且 B 上的信号,线程 4 可能会在线程 3 之前醒来,这不是我想要的。
任何指示都将受到高度赞赏。
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用条件变量来解决这个问题。不要让线程 4 仅等待线程 2 设置的条件,而是让它等待仅在线程 1、线程 2 和线程 3 的所有完成其操作后设置的条件
: 1 已经完成了它的工作,它设置了它的部分条件:
...对于线程 2 和线程 3 也是如此。线程 4 仅在设置了所有标志后才会继续。
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:
When Thread 1 has done its thing, it sets its part of the condition:
...and likewise for Thread 2 and Thread 3. Thread 4 will only continue once all the flags have been set.
使用 信号量:让线程 1-3 中的每个线程发布信号量,并让线程 4等待信号量而不是条件变量 3 次。
您需要使用
sem_init(3)
或 < a href="http://linux.die.net/man/3/sem_open" rel="nofollow">sem_open(3)
创建信号量,sem_post(3)
发布信号量,sem_wait(3)
等待信号量,然后sem_destroy(3)
(如果使用sem_init) 或
sem_close(3)
和sem_unlink(3)
(如果使用sem_open) 来销毁信号量。
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)
orsem_open(3)
to create the semaphore,sem_post(3)
to post the semaphore,sem_wait(3)
to wait on the semaphore, and then eithersem_destroy(3)
(if created withsem_init
) orsem_close(3)
andsem_unlink(3)
(if created withsem_open
) to destroy the semaphore.为此,请考虑使用 ZeroMQ 的进程内信令。 ZeroMQ 实现了一种消息传递模型,可有效用于协调线程以及进程间或网络消息传递。
有关更多信息:http://api.zeromq.org/2-1-1 :zmq-inproc
下面是使用 ZeroMQ 和 Java 在线程之间进行负载平衡的示例。
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.