生产者和消费者

#include <iostream>
#include <queue>
#include <pthread.h>

using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

queue<int> q;

void* comsumer(void* arg){
    for(;;){
        pthread_mutex_lock(&mutex);
        while(q.empty()){
            pthread_cond_wait(&cond,&mutex);
        }
        while(!q.empty()){
            cout<<"comsume:"<< q.front() <<endl;
            q.pop();
        }
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void* producer(void* arg){
    int number = *(int*)arg;
    for(int i = 0; i < number; i++){
        pthread_mutex_lock(&mutex);
        q.push(i);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}


int main(){
    pthread_t comsumer_thread;
    pthread_t producer_thread;
    pthread_create(&comsumer_thread,NULL,comsumer,NULL);
    int num = 1000;
    pthread_create(&producer_thread,NULL,producer, &num);
    pthread_join(comsumer_thread, NULL);
    pthread_join(producer_thread, NULL);
    return 0;
}

posted on 2016-06-07 22:33  shaolw  阅读(128)  评论(0编辑  收藏  举报

导航