#include <stdlib.h>#include <pthread.h>#include <stdio.h>struct msg{struct msg *next;int num;};struct msg *head;pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;void *consumer(void *p){struct msg *mp;while(1){pthread_mutex_lock(&lock); //1 : 消费者先加锁printf("consumer is lock.\n");while(NULL == head){pthread_cond_wait(&has_product,&lock); //2: 消费者循环等待}mp = head;head = mp->next;pthread_mutex_unlock(&lock); //3:消费者释放锁printf("consumer is unlock.\n");printf("Consume %d\n",mp->num);free(mp);sleep(rand() % 5);}}void *producer(void *p){struct msg *mp;while(1){mp = malloc(sizeof(struct msg));mp->num = rand() % 1000 + 1;printf("Produce %d\n",mp->num);pthread_mutex_lock(&lock); //4:生产者加锁,但此时消费者并未释放锁,但此处却加锁成功了???printf("producer is lock.\n");mp->next = head;head = mp;pthread_mutex_unlock(&lock); //5:生产者释放锁printf("producer is unlock.\n");pthread_cond_signal(&has_product);sleep(rand() % 5);}}int main(int argc, char *argv[]){pthread_t pid,cid;srand(time(NULL));pthread_create(&cid,NULL,consumer,NULL); //6:让消费者先运行,加锁,然后进入循环等待状态sleep(3);pthread_create(&pid,NULL,producer,NULL); pthread_join(pid,NULL);pthread_join(cid,NULL);return 0;}测试输出:consumer is lock. //此处已经加锁Produce 728producer is lock. //此处锁并未释放,但却获得了锁,为什么呢???producer is unlock.consumer is unlock.Consume 728Produce 630producer is lock.producer is unlock.consumer is lock.consumer is unlock.Consume 630consumer is lock.
1 回答
慕容708150
TA贡献1831条经验 获得超4个赞
环等待其实是这样的:检查条件满不满足,不满足就解锁,然后等,等到了要检测的时候,又上锁,然后检查,不满足就解锁。
也就是说,进了pthread_cond_wait函数以后,它就释放了lock,然后在has_product上等待,等到has_product被触发了,就再上锁,然后出函数。你的消费者线程调用了pthread_cond_wait以后,就释放了锁,然后这个函数不返回(这个函数不返回你的代码就不会运行下去),等到has_product触发了,这个函数就获取锁,然后返回。
再解释一下,就是调用这个函数之前,你这个线程是拿到锁的;出了这个函数,你的线程也还是拿到锁的;但是进了这个函数还没出来的过程中,你的线程会释放锁。
- 1 回答
- 0 关注
- 66 浏览
添加回答
举报
0/150
提交
取消