这是使用条件变量的正确方法吗?
Is this the correct way to use condition variables?
下面的代码有什么风险吗?有人可以解释一下为什么我必须使用 pthread_cond_broadcast
而不是 pthread_cond_signal
吗?
#include <pthread.h>
unsigned int target_id;
pthread_mutex_t my_mytex;
pthread_cond_t my_cond;
void *print_item_(void *ar)
{
int id = *((unsigned int*)ar);
pthread_mutex_lock(&my_mytex);
while (id != target_id)
pthread_cond_wait(&my_cond, &my_mytex);
printf("%u\n", id);
target_id++;
pthread_cond_broadcast(&my_cond);
pthread_mutex_unlock(&my_mytex);
free(ar);
return NULL;
}
int main()
{
pthread_t *threads;
unsigned int *var;
int i;
target_id = 1;
pthread_mutex_init(&my_mytex, NULL);
pthread_cond_init(&my_cond, NULL);
threads = (pthread_t*)malloc(sizeof(pthread_t)*50);
for(i = 1; i < 50; i++)
{
var = (unsigned int*)malloc(sizeof(unsigned int));
var[0] = i+1;
pthread_create(&threads[i], NULL, print_item_, (void*)var);
}
var = (unsigned int*)malloc(sizeof(unsigned int));
var[0] = 1;
pthread_create(&threads[0], NULL, print_item_, (void*)var);
for(i = 0; i < 50; i++)
pthread_join(threads[i], NULL);
free(threads);
}
您使用条件变量的方式是正确的。
您需要使用 pthread_cond_broadcast()
的原因是,在您的设计中,您可能有多个线程在等待条件变量,如果发出条件信号,其中只有一个特定的线程准备好继续。这意味着你需要使用 pthread_cond_broadcast()
来唤醒它们 all ,这确保了可以继续进行的单个线程将被唤醒。
pthread_cond_signal()
是一种优化 - 它唤醒了一个等待线程,但没有指定是哪一个,所以它只适用于 any 的情况如果唤醒,等待线程将能够继续。
顺便说一下,在调用 pthread_create()
.
的循环中,特殊外壳线程 1 (i == 0
) 没有任何收获
下面的代码有什么风险吗?有人可以解释一下为什么我必须使用 pthread_cond_broadcast
而不是 pthread_cond_signal
吗?
#include <pthread.h>
unsigned int target_id;
pthread_mutex_t my_mytex;
pthread_cond_t my_cond;
void *print_item_(void *ar)
{
int id = *((unsigned int*)ar);
pthread_mutex_lock(&my_mytex);
while (id != target_id)
pthread_cond_wait(&my_cond, &my_mytex);
printf("%u\n", id);
target_id++;
pthread_cond_broadcast(&my_cond);
pthread_mutex_unlock(&my_mytex);
free(ar);
return NULL;
}
int main()
{
pthread_t *threads;
unsigned int *var;
int i;
target_id = 1;
pthread_mutex_init(&my_mytex, NULL);
pthread_cond_init(&my_cond, NULL);
threads = (pthread_t*)malloc(sizeof(pthread_t)*50);
for(i = 1; i < 50; i++)
{
var = (unsigned int*)malloc(sizeof(unsigned int));
var[0] = i+1;
pthread_create(&threads[i], NULL, print_item_, (void*)var);
}
var = (unsigned int*)malloc(sizeof(unsigned int));
var[0] = 1;
pthread_create(&threads[0], NULL, print_item_, (void*)var);
for(i = 0; i < 50; i++)
pthread_join(threads[i], NULL);
free(threads);
}
您使用条件变量的方式是正确的。
您需要使用 pthread_cond_broadcast()
的原因是,在您的设计中,您可能有多个线程在等待条件变量,如果发出条件信号,其中只有一个特定的线程准备好继续。这意味着你需要使用 pthread_cond_broadcast()
来唤醒它们 all ,这确保了可以继续进行的单个线程将被唤醒。
pthread_cond_signal()
是一种优化 - 它唤醒了一个等待线程,但没有指定是哪一个,所以它只适用于 any 的情况如果唤醒,等待线程将能够继续。
顺便说一下,在调用 pthread_create()
.
i == 0
) 没有任何收获