I've written a little to program to try out pthread conditional waits. But the problem is that there is no guarantee that a signal when sent out will be caught, thereby the thread losing the wakeup. How do I get around this?
#include<stdio.h>
#include<pthread.h>
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_func1(void* arg){
printf("thread1 started
");
pthread_mutex_lock(&mutex);
printf("thread1: signalling
");
pthread_cond_signal(&cond);
printf("thread1: signalled
");
pthread_mutex_unlock(&mutex);
printf("thread1: exiting
");
pthread_exit(0);
}
void *thread_func2(void* arg){
printf("thread2 started
");
pthread_mutex_lock(&mutex);
printf("thread2: waiting for signal..
");
pthread_cond_wait(&cond, &mutex);
printf("thread2: signal received
");
pthread_mutex_unlock(&mutex);
printf("thread2: exiting
");
pthread_exit(0);
}
int main(int argc, char** argv){
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, thread_func1, NULL);
pthread_create(&thread2, NULL, thread_func2, NULL);
pthread_join(thread1, 0);
pthread_join(thread2, 0);
return 0;
}
Here is an output from a run:
thread1 started
thread1: signalling
thread2 started
thread2: waiting for signal..
thread1: signalled
thread1: exiting
// nothing happens now; where is the signal??
Here's from another one (which works):
thread2 started
thread2: waiting for signal..
thread1 started
thread1: signalling
thread1: signalled
thread1: exiting
thread2: signal received
thread2: exiting
// program successfully exits
I'm not concerned about any kind of critical section for now, so I haven't used any locks.
How do I ensure this thing works for each run?
Edit: I have edited the code as per alk's answer below. I have added the initializers and locks. The original code I posted is here.
See Question&Answers more detail:os