I am working on a project and trying to use pthread_cond_wait()
and pthread_cond_signal()
to synchronize two threads.
My code looks something like this:
pthread_mutex_t lock_it = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t write_it = PTHREAD_COND_INITIALIZER;
int main(int argc, char**argv)
{
pthread_t t_send_segments, t_recv_acks;
pthread_create(&t_send_segments, NULL, send_segments, (void*)NULL);
pthread_create(&t_recv_acks, NULL, recv_acks, (void*)NULL);
pthread_join(t_recv_acks, (void**)NULL);
pthread_mutex_destroy(&lock_it);
pthread_cond_destroy(&write_it);
}
void* send_segments(void *v) {
for(;;) {
pthread_mutex_lock(&lock_it);
printf("s1\n");
printf("s2\n");
pthread_cond_wait(&write_it, &lock_it);
printf("s3\n");
printf("s4\n");
printf("s5\n");
pthread_mutex_unlock(&lock_it);
}
return 0;
}
void* recv_acks(void *v) {
for(;;) {
pthread_mutex_lock(&lock_it);
printf("r1\n");
pthread_cond_signal(&write_it);
printf("r2\n");
pthread_mutex_unlock(&lock_it);
}
return 0;
}
The expected output is:
s1
s2
r1
s3
s4
s5
s1
s2
r2
r1
s3
s4
s5
(etc)
My output doesn't follow this pattern at all. Clearly I have a logic error somewhere, but I'm not understanding where. Why doesn't the recv_acks()
thread always yield when it hits the pthread_cond_signal()
- since the pthread_cond_wait()
always executes first (because of the order in which I create the threads) and the cond_wait()
always executes since its in the critical section?