#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 : 消費(fèi)者先加鎖printf("consumer is lock.\n");while(NULL == head){pthread_cond_wait(&has_product,&lock); //2: 消費(fèi)者循環(huán)等待}mp = head;head = mp->next;pthread_mutex_unlock(&lock); //3:消費(fèi)者釋放鎖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:生產(chǎn)者加鎖,但此時(shí)消費(fèi)者并未釋放鎖,但此處卻加鎖成功了???printf("producer is lock.\n");mp->next = head;head = mp;pthread_mutex_unlock(&lock); //5:生產(chǎn)者釋放鎖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:讓消費(fèi)者先運(yùn)行,加鎖,然后進(jìn)入循環(huán)等待狀態(tài)sleep(3);pthread_create(&pid,NULL,producer,NULL); pthread_join(pid,NULL);pthread_join(cid,NULL);return 0;}測(cè)試輸出:consumer is lock. //此處已經(jīng)加鎖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.
程序如下:個(gè)人理解的下面的程序應(yīng)該產(chǎn)生死鎖?
30秒到達(dá)戰(zhàn)場(chǎng)
2023-03-02 18:14:23