1. 程式人生 > >靜態分配互斥量與動態分配互斥量的區別和例項分析

靜態分配互斥量與動態分配互斥量的區別和例項分析

#include "stdio.h"
#include <stdlib.h>
#include <pthread.h>


#define N_CONSUMER 3 //消費者數量
#define N_PRODUCER 2 //生產者數量
#define C_SLEEP 1 //控制 consumer 消費的節奏
#define P_SLEEP 1 //控制 producer 生產的節奏

pthread_t ctid[N_CONSUMER];//消費者執行緒陣列
pthread_t ptid[N_PRODUCER];//生產者執行緒陣列

pthread_cond_t notFull,notEmpty;//定義條件變數,notFull緩衝區不滿;notEmpty緩衝區不空
pthread_mutex_t buf = PTHREAD_MUTEX_INITIALIZER;//靜態分配互斥量,用於鎖住緩衝區
int begin = 0,end = 0, cnt = 0, max = 4;//從 begin 到 end(不含end) 代表產品,cnt 代表產品數量,max 代 表庫房的容量,即最多生產多少產品 void * consumer(void * pidx)//consumer thread idx { printf("consumer thread id %d\n",*((int *)pidx)); while(1) { pthread_mutex_lock(&buf); while(cnt == 0){//當緩衝區空時 pthread_cond_wait(¬Empty,&buf);//阻塞並等待不空的訊號 } printf("consume %d\n",begin); begin = (begin+1)%max; cnt--; pthread_mutex_unlock(&buf); sleep(C_SLEEP); pthread_cond_signal(¬Full); } pthread_exit((void *)0); } void * producer(void * pidx)//producer thread idx { printf("producer thread id %d\n",*((int *)pidx)); while(1) { pthread_mutex_lock(&buf); while(cnt == max){//當緩衝區滿時 pthread_cond_wait(¬Full,&buf); } pthread_mutex_lock(&buf); while(cnt == 0){//當緩衝區空時 pthread_cond_wait(¬Empty,&buf);//阻塞並等待不空的訊號 } printf("consume %d\n",begin); begin = (begin+1)%max; cnt--; pthread_mutex_unlock(&buf); sleep(C_SLEEP); pthread_cond_signal(¬Full); } pthread_exit((void *)0); } void * producer(void * pidx)//producer thread idx { printf("producer thread id %d\n",*((int *)pidx)); while(1) { pthread_mutex_lock(&buf); while(cnt == max){//當緩衝區滿時 pthread_cond_wait(¬Full,&buf); } int main() { int i = 0; for(i = 0; i < N_CONSUMER; i++) { int * j = (int *) malloc(sizeof(int)); *j = i; if(pthread_create(&ctid[i],NULL,consumer,j) != 0) { perror("create consumer failed\n"); exit(1); } } for(i = 0; i < N_PRODUCER; i++) { int * j = (int *) malloc(sizeof(int)); *j = i; if(pthread_create(&ptid[i],NULL,producer,j) != 0) { perror("create producer failed\n"); exit(1); } } while(1) { sleep(10); } return 0; }