Linux C++ 面向对象多线程编程实例之“生产者-消费者”

Linux C++ 面向对象多线程编程实例之“生产者-消费者”

问题1

生产者-消费者模型

解决方案:

两个线程,一个共享变量。

源码:

#include <iostream>

#include <pthread.h>

using namespace std;

//The Number of Products.

volatile int _nCurrProductor = 0;

//Action Lock.

pthread_mutex_t _dealmutex;

 

void* producer(void *arg)

{

    while(true)

    {

        pthread_mutex_lock(&_dealmutex);

        _nCurrProductor ++;

        cout<<"I Produced One."<<endl;

        pthread_mutex_unlock(&_dealmutex);

    }

}

 

void* customer(void *arg)

{

    while(true)

    {

        pthread_mutex_lock(&_dealmutex);

        if(_nCurrProductor > 0)

        {

            _nCurrProductor --;

            cout<<"Haha, I Ate One."<<endl;

        }

        else

        {

            cout<<"Baby, Come On. I am hungry."<<endl;

        }

        pthread_mutex_unlock(&_dealmutex);

    }

}

 

int main(int argc, char** argv)

{

    cout<<"Let's Go!!!"<<endl;

    pthread_mutex_init(&_dealmutex, NULL);

 

    pthread_t pt1;

    pthread_t pt2;

    int pret2 = pthread_create(&pt2, NULL, customer, NULL);

    int pret1 = pthread_create(&pt1, NULL, producer, NULL);

    if(pret1 != 0 || pret2 != 0)

    {

        cout<<"Thread Create Failed."<<endl;

        exit(1);

    }

 

    while(true)

    {

 

    }

 

    pthread_join(pt1, NULL);

    pthread_join(pt2, NULL);

 

    cout<<"Game Over!"<<endl;

    return 0;

}

 

相关参考:

http://rayljh.bokee.com/4911139.html

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值