pthread_mutex_lock与pthread_cond_wait的疑惑

pthread_mutex_lock和pthread_cond_wait的组合使用可以用于线程间的同步和通信。具体来说,pthread_mutex_lock用于保护共享资源,pthread_cond_wait则用于等待条件变量的发生。 当一个线程需要访问共享资源时,它首先需要获取互斥锁,如果互斥锁已经被其他线程占用,则该线程会被阻塞。当该线程成功获取互斥锁后,它可以访问共享资源,并且可以通过条件变量来等待某个条件的发生。如果条件不满足,则该线程会被阻塞,并且会自动释放互斥锁,以便其他线程可以访问共享资源。当条件满足时,另一个线程可以通过pthread_cond_signal或pthread_cond_broadcast来通知等待的线程,使其重新竞争互斥锁。 下面是一个简单的例子: ```c pthread_mutex_t mutex; pthread_cond_t cond; int count = 0; void* producer(void* arg) { while (1) { pthread_mutex_lock(&mutex); count++; printf("producer: count = %d\n", count); pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex); sleep(1); } } void* consumer(void* arg) { while (1) { pthread_mutex_lock(&mutex); while (count == 0) { pthread_cond_wait(&cond, &mutex); } count--; printf("consumer: count = %d\n", count); pthread_mutex_unlock(&mutex); sleep(1); } } int main() { pthread_t tid1, tid2; pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_create(&tid1, NULL, producer, NULL); pthread_create(&tid2, NULL, consumer, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); return 0; } ``` 在这个例子中,生产者线程不断地增加count的值,并通过pthread_cond_signal来通知等待的消费者线程。消费者线程则通过pthread_cond_wait来等待count的值不为0。当count的值不为0时,消费者线程减少count的值,并通过printf来输出count的值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值