Linux-----多线程生产者与消费者模型

生产者与消费者模型

原理:

        使用链表将产品连接起来,当单表为空时,消费者等待,生产者开始生成,并将产品连接到链表上,消费者每次消费后,改变头结点的指向。

模型:

Linux-----多线程生产者与消费者模型_第1张图片

代码:

#include
#include
#include
#include
#include

#define CONSUMERS_COUNT 2
#define PRODUCERS_COUNT 2
//定义条件变量与互斥量
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_t thread[CONSUMERS_COUNT+PRODUCERS_COUNT];
//临界资源
struct msg{
    struct msg* next;
    int num;
};
//创建头结点
struct msg* head = NULL;
//消费函数
void* consumer(void *arg){
    struct msg *mp;
    for(;;){
        //加锁
        pthread_mutex_lock(&mutex);
        while(head==NULL){
            printf("%d begin wait a condition...\n",(int *)arg);
            //等待
            pthread_cond_wait(&cond,&mutex);
        }
        printf("%d end wait a condition...\n",(int *)arg);
        printf("%d begin consume product...\n",(int*)arg);
        mp= head;
        head = mp->next;
        //释放锁
        pthread_mutex_unlock(&mutex);
        printf("consume %d\n",mp->num);
        free(mp);
        printf("%d end consume product ...\n",(int*)arg);
        sleep(rand()%5);
    }
}
//生产函数
void* producer(void* arg){
    struct msg *mp;
    for(;;){
        printf("%d begin produce product...\n",(int *)arg);
        mp = (struct msg*)malloc(sizeof(struct msg));
        mp->num = rand()%100+1;
        printf("produce %d\n",mp->num);
        //加锁
        pthread_mutex_lock(&mutex);
        mp->next = head;
        head = mp;
        printf("%d end produce product...\n",(void*)arg);
        //唤醒
        pthread_cond_signal(&cond);
        //释放锁 
        pthread_mutex_unlock(&mutex);
        sleep(rand()%5);
    }
}
int main(void){
    //初始化
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&cond,NULL);
    int i = 0;
    srand((unsigned int)time(NULL));
    //创建消费者线程
    for(;i

你可能感兴趣的:(操作系统)