gpt4 book ai didi

我可以使用 pthread_cond_wait(,) 同时向多个线程发出信号吗?

转载 作者:行者123 更新时间:2023-11-30 19:28:17 28 4
gpt4 key购买 nike

我正在编写各种代码片段,看看会发生什么。下面的代码旨在延迟所有线程,直到所有线程都到达代码中的某个点,然后使每个线程打印一个独特的数字。由于线程都这样做,因此数字应该以随机顺序出现。

我当前的问题是我让它们的线程忙于等待。如果线程数量变大,程序速度会显着减慢。

我想通过使用信号来改变这一点,我找到了 pthread_cond_wait() 来实现这一点,但是我不知道如何使用它来向所有线程发出信号,表示它们将被唤醒。

#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;
}

编辑:我将代码更改为以下内容,但是它仍然不起作用:/

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 上阻塞的所有线程。

pthread_cond_signal() 函数应至少解除对指定条件变量 cond 上阻塞的一个线程的阻塞(如果有任何线程在 cond 上阻塞) )。

关于我可以使用 pthread_cond_wait(,) 同时向多个线程发出信号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54224992/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com