Reputation: 1103
Are there any risks with the code below? Can someone please explain why I have to use pthread_cond_broadcast
instead of pthread_cond_signal
in my case please?
#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);
}
Upvotes: 1
Views: 109
Reputation: 239341
The way you're using condition variables there is correct.
The reason you need to use pthread_cond_broadcast()
is that in your design, you might have multiple threads waiting on the condition variable where only a particular one of them will be ready to proceed if the condition is signalled. This means you need to use pthread_cond_broadcast()
to wake them all up, which ensures that the single thread that can proceed will be woken.
pthread_cond_signal()
is an optimisation - it wakes one of the waiting threads, but it isn't specified which one, so it's only applicable for situations where any of the waiting threads will be able to proceed if woken.
By the way, nothing is gained by special-casing thread 1 (i == 0
) in the loop that calls pthread_create()
.
Upvotes: 1