利用线程解决生产者——消费者问题

ubuntu 下qt creator 比 codeblocks 更好用。然而vs比qt creator 好用很多,可是win不支持pthread.h。qt creator缺点是要配置一下才能输入中文。谷歌一下就行。超级无敌爽。至于vim,应该是ide装vim插件,利用vim的普通模式,而不是vim装ide打功能。。。vim有时编译不好,像多线程链接就要加上pthread,用vim的话没用工程配置的概念。


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

#define MAX 1000

pthread_mutex_t the_mutex;//互斥量

pthread_cond_t condc,condp;//条件变量

int buffer=0;//缓冲内容

void *producer(void *ptr)
{   
    for(int i=1;i<=MAX;i++)
    {
        pthread_mutex_lock(&the_mutex);//互斥使用缓冲区
        while(buffer!=0)
        {
            pthread_cond_wait(&condp,&the_mutex);//阻塞以等待信号
        }

        buffer=i;
        printf("producer %d\n",i);
        pthread_cond_signal(&condc);//向另一个进程发出信号唤醒
        pthread_mutex_unlock(&the_mutex);//释放缓冲区
    }
    pthread_exit(0);
}

void *consumer(void *ptr)
{
    int i;
    for(i=1;i<=MAX;i++)
    {
        pthread_mutex_lock(&the_mutex);
        while(buffer==0)
            pthread_cond_wait(&condc,&the_mutex);
        printf("consumer %d\n",buffer);
        buffer=0;
        pthread_cond_signal(&condp);
        pthread_mutex_unlock(&the_mutex);
    }
    pthread_exit(0);
}


int main()
{
    pthread_t pro,con;//线程号
    pthread_mutex_init(&the_mutex,0);//创建一个互斥变量
    pthread_cond_init(&condc,0);//创建一个条件变量
    pthread_cond_init(&condp,0);
    pthread_create(&con,0,consumer,NULL);//创建线程
    pthread_create(&pro,0,producer,NULL);
    pthread_join(pro,0);//如果没有pthread_join;主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了
    pthread_join(con,0);//加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行
    //pthread_join函数会让主线程阻塞,直到所有线程都已经退出

    pthread_cond_destroy(&condc);//销毁条件变量
    pthread_cond_destroy(&condp);
    pthread_mutex_destroy(&the_mutex);//销毁互斥变量

}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值