我正在做一个项目并尝试使用 pthread_cond_wait()
和 pthread_cond_signal()
同步两个线程。
我的代码看起来像这样:
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;
}
预期的输出是:
s1
s2
r1
s3
s4
s5
s1
s2
r2
r1
s3
s4
s5
(etc)
我的输出根本不遵循这种模式。显然我在某处有逻辑错误,但我不明白在哪里。为什么recv_acks()
线程在遇到- 因为总是首先执行(因为我创建线程的顺序)并且总是在临界区之后执行,所以它在命中时并不总是屈服?pthread_cond_signal()
pthread_cond_wait()
cond_wait()