生產者與消費者模型


typedef struct node{
    struce node* next;
    int val;
}Node;

Node* head=NULL;//頭結點初始化爲空

pthread_mutex_t mutex;
pthread_cond_t cond;

void *producer(void *arg){
    while(1){
        Node* pNew=(Node*) malloc(sizeof(Node));//生產一個新節點
        pNew->val=rand()%1000;
        //開始把生產的節點加入到鏈表中
        pthread_mutex_lock(&mutex);
        //採用頭插法
        pNew->next=head;
        head=pNew;
        //輸出產品信息
        printf("Producer's id=%lu,pNew->val=%d\n",pthread_self(),pNew->data);
        //插入完成後解鎖
        pthread_mutex_unlock(&mutex);
        //解鎖後通知消費者
        pthread_cond_signal(&cond);
        sleep(rand()%3);
    }
    return NULL;
}

void *consumer(void *arg){
    while(1){
        //消費前,先嚐試解鎖
        pthread_mutex_unlock(&mutex);
        if(head==NULL){//還沒有產品時
            pthread_cond_wait(&cond,&mutex);//cond滿足時,解除阻塞
        }
        //有產品時,開始消費
        Node* pDel=head;
        head=head->next;
        printf("consumer's id=%lu,pNew->val=%d\n",pthread_self(),pNew->data);
        free(pDel);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章