代码编辑器

//多线程生产者与消费者模型,multithrd.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>

#define N 10   //缓冲的大小 size of cache

int i = 0;
int j = 0;
int pPos = 0;   //生产者放产品的位置 position of producer
int cPos = 0;   //消费者取产品的位置 position of consumer
int data = 0;   //生产的产品 product
char product1[20];  //存放来自管道的数据,已消费的产品 consumed from pipe
char product2[20];  //即将写入管道的数据,已消费的产品 consumed to pipe
int buffer[N];   //放置产品的缓冲区 the cache
int producerID = 0;   //生产者ID producer ID
int consumerID = 0;   //消费者ID consumer ID
int pipe_info[2];   //管道 the pipe
pthread_mutex_t mutex;   //防止线程竞争的互斥量 mutex to make sure only one thread access the cache at one time
pthread_cond_t buffererReadCond=PTHREAD_COND_INITIALIZER;   //消费者的条件变量 conditional variable of read()
pthread_cond_t buffererWriteCond=PTHREAD_COND_INITIALIZER;   //生产者的条件变量

//显示当前缓冲的情况 show the state of the cache
void showcache()
{
    printf("The state is : ");
    for(i = 0; i < N; i++)
        printf("%d ", buffer[i]);
    printf("\n");
}

//计算缓冲里面的产品数量 calculate the number of products in cache
int count()
{
    int count=0;
    for(i=0; i<N; i++)
    {
        if(buffer[i] != 0)
            count++;
    }
    return count;

}
//设置管道为非阻塞管道 let the io of the pipe no blocking
int setNoblocking(int fd)
{
    int val;
    if((val=fcntl(fd, F_GETFL, 0))<0) {
        printf("fcntl getfl error \n");
        return -1;
    }
    val |=O_NONBLOCK;
    if(fcntl(fd, F_SETFL, val)<0) {
        printf("fcntl set error \n");
        return -1;
    }
    return 0;
}

//生产者模型 producer method
void *producer()
{
    int id = ++producerID;
    while(1)
    {
        sleep(1);
        pthread_mutex_lock(&mutex);   //锁住互斥量 lock
        setNoblocking(pipe_info[0]);
        if(count() >= N)   //如果缓冲满了
        {
            pthread_cond_wait(&buffererWriteCond, &mutex);   //线程挂起,等待某个条件 WAIT FOR A CONDITION
        }
        j++;
        pPos = pPos % N;
        buffer[pPos] = ++data;   //生产一个产品 produce a product "data" in "pPos" position
        printf("producerID is %d, produce %d at %d.\t", id, data, pPos+1);
        showcache();
        ++pPos;   //下个位置 NEXT POSITION
        if((read(pipe_info[0], product1, 20))>0)   //从管道读取数据 read data from PIPE
            printf("-------- The %s is consumed. \n", product1);   //显示已经消费的产品 show the consumed product
        pthread_cond_signal(&buffererReadCond);   //唤醒某个等待条件的消费者进程 TELL CONSUMER THE CONDITION IS OK!
        pthread_mutex_unlock(&mutex);   //解锁 unlock
        if(j > 100)
		    break;   //退出循环
    }
    exit(0);
}

//消费者模型 consumer method
void *consumer()
{
    int id = ++consumerID;
    while(1)
    {
        sleep(1);
        pthread_mutex_lock(&mutex);
        setNoblocking(pipe_info[1]);
        if(count() <= 0)
        { //如果缓冲没有产品 if no product to consume
            pthread_cond_wait(&buffererReadCond, &mutex);   //线程挂起,等待某个条件爱你唤醒 then sleep this thread
        }
        i++;
        cPos = cPos % N;
        sprintf(product2, "%d", buffer[cPos]);   //what consumed is stored in product
        buffer[cPos] = 0;
        printf("consumerID is %d, consume %s at %d.\t", id, product2, cPos+1);
        showcache();
        ++cPos;//下个位置 NEXT
        printf("++++++++ I consume %s \n", product2);   //显示被消费的产品 SHOW WHAT CONSUMED
        write(pipe_info[1], product2, 20);   //写入管道 WRITE DATA TO PIPE
        pthread_cond_signal(&buffererWriteCond);   //唤醒某个生产者进程 TELL PRODUCER COND IS OK
        pthread_mutex_unlock(&mutex);   //解锁 UNLOCK
        if(i > 100)
		    break;   //退出循环
    }
    exit(0);
}

int main(int argc,char *argv[])
{
    if(argc!=3)   //如果参数个数不合法
    {
        printf(" Usage : ./a.out int1 int2 \n");
        exit(0);
    }
    else
    {
        if(pipe(pipe_info)<0)
        {
            printf("Fail to creat pipe.\n");
            exit(0);
        }
        
        //初始化缓冲
        for(i=0; i<N; ++i)
        {
            buffer[i] = 0;
        }

        int n1=atoi(argv[1]);//将字符转化为数字 change to a INT
        int n2=atoi(argv[2]);

        pthread_t *id1;
        pthread_t *id2;
        id1=(pthread_t *)malloc((n1)*sizeof(pthread_t));//生产者指针 POINTER OF THREAD FOR PRODUCER
        id2=(pthread_t *)malloc((n2)*sizeof(pthread_t));//消费者指针 FOR CONSUMER


        //初始化互斥量 init the mutex
        if(pthread_mutex_init(&mutex, NULL) != 0)
        {
            printf("Fail to init mutex.\n");
            exit(1);
        }
        //创建生产者线程 create some producer threads
        for(i = 0; i < n1; i++)
        {
            if(pthread_create(&id1[i], NULL, producer, (void *)(&i)) != 0)
            {
                printf("Fail to creat producer %d.\n", i);
                exit(1);
            }
        }
        //创建消费者线程 create some consumer threads
        for(i = 0; i < n2; i++)
        {
            if(pthread_create(&id2[i], NULL, consumer, NULL) != 0)
            {
                printf("Fail to creat consumer %d.\n", i);
                exit(1);
            }
        }
        //销毁线程 destroy threads
        for(i = 0; i < n1; i++)
        {
            pthread_join(id1[i],NULL);
        }
        for(i = 0; i < n2; i++)
        {
            pthread_join(id2[i],NULL);
        }
        //销毁互斥量,关闭条件变量
        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&buffererReadCond);
        pthread_cond_destroy(&buffererWriteCond);
        return 0;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值