我可以使用pthread_cond_wait(,)同时发信号通知多个线程吗? [英] Can I signal multiple threads simultaneously with pthread_cond_wait(,)?
问题描述
我正在编写各种代码段,看看会发生什么.下面的代码旨在延迟所有线程,直到所有线程都到达代码中的某个点为止,然后使每个线程打印一个唯一的数字.由于所有线程都执行此操作,因此编号应该以随机顺序出现.
I am writing various code snippets and see what happens. The code below was intended to delay all threads until all reached a certain point in the code and then make each print a distinctive number. Since the threads all do that, the numbers should occur in a random order.
我当前的问题是我让他们的线程忙于等待.如果线程数变大,程序将显着减慢速度.
My current problem is that I keep they threads busy waiting. If the number of threads gets big, the program slows down significantly.
我想通过使用信号来更改它,为此我找到了pthread_cond_wait()
,但是我看不到如何使用它来向所有线程发出信号,请它们唤醒.
I would like to change that by using signals, I found pthread_cond_wait()
for that, however I don't see how one would use that to signal all threads that they would please wake up.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define threads 10
int counter=0;
pthread_mutex_t lock;
void handler(void *v) {
pthread_mutex_lock(&lock);
counter++;
printf("%d\n", counter);
pthread_mutex_unlock(&lock);
while(counter != threads); // busy waiting
printf("I am first! %d\n", v);
}
int main() {
pthread_t t[threads];
for(int i =0; i < threads; i++) {
pthread_create(&t[i], NULL, handler, (void*) i);
}
for(int i =0; i < threads; i++) {
pthread_join(t[i], NULL);
}
return 0;
}
我将代码更改为以下代码,但是,它仍然不起作用:/
I changed the code to the following, however, it still does not work :/
pthread_mutex_t lock;
pthread_cond_t cv;
void handler(void *v) {
pthread_mutex_lock(&lock);
pthread_cond_wait(&cv, &lock);
printf("I am first! %d\n", v);
pthread_mutex_unlock(&lock);
}
int main() {
pthread_t t[threads];
for(int i =0; i < threads; i++)
pthread_create(&t[i], NULL, handler, (void*) i);
sleep(2);
pthread_cond_signal(&cv);
for(int i =0; i < threads; i++)
pthread_join(t[i], NULL);
return 0;
}
推荐答案
使用broadcast()
?
http://pubs.opengroup.org/onlinepubs/009696699/functions /pthread_cond_broadcast.html
pthread_cond_broadcast()
函数应取消阻止当前在指定条件变量cond
上阻塞的所有线程.
The pthread_cond_broadcast()
function shall unblock all threads currently blocked on the specified condition variable cond
.
pthread_cond_signal()
函数应解除对至少一个在指定条件变量cond
上被阻塞的线程的阻塞(如果在cond
上任何线程被阻塞).
The pthread_cond_signal()
function shall unblock at least one of the threads that are blocked on the specified condition variable cond
(if any threads are blocked on cond
).
这篇关于我可以使用pthread_cond_wait(,)同时发信号通知多个线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!