码迷,mamicode.com
首页 > 编程语言 > 详细

生成者消费者(线程同步,互斥,条件变量)

时间:2014-11-05 21:06:30      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   for   sp   div   on   log   

#include <unistd.h>
#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];//consumer thread id
pthread_t ptid[N_PRODUCER];//producer thread id

pthread_cond_t notFull,notEmpty;//缓冲区不满;缓冲区不空
pthread_mutex_t buf = PTHREAD_MUTEX_INITIALIZER;//用于锁住缓冲区

//从 begin 到 end(不含end) 代表产品
//cnt 代表产品数量
//max 代表库房的容量,即最多生产多少产品
int begin = 0,end = 0, cnt = 0, max = 4;

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(&notEmpty,&buf);
        }
        printf("consume %d\n",begin);
        begin = (begin+1)%max;
        cnt--;
        pthread_mutex_unlock(&buf);
        sleep(C_SLEEP);
        pthread_cond_signal(&notFull);
    }
    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(&notFull,&buf);
        }
        printf("produce %d\n",end);
        end = (end+1)%max;
        cnt++;
        pthread_mutex_unlock(&buf);
        sleep(P_SLEEP);
        pthread_cond_signal(&notEmpty);
    }
    pthread_exit((void *)0);
}

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;
}

 

生成者消费者(线程同步,互斥,条件变量)

标签:style   blog   io   color   for   sp   div   on   log   

原文地址:http://www.cnblogs.com/kangbry/p/4077296.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!