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