bdr54321
3/24/2020 - 12:40 AM

条件变量

#include <iostream>
#include <stdio.h>

#include <unistd.h>
#include <pthread.h>

using std::cout;
int MAX_BUF = 5;
int num = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZERZZ;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void *producer(void *)
{
    while(true){
        pthread_mutex_lock(&mutex);
        while(num >= MAX_BUF){
            //等待
            cout << "线程一:缓存区满了,等待消费者消费...\n";
            pthread_cond_wait(&cond, &mutex);   
        }
        num+=1;
        cout << "线程一:num = " << num << ", 通知消费者....\n";
        sleep(1);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}


void *consumser(void *)
{
    while(true){
        pthread_mutex_lock(&mutex);
        while(num <= 0){
            //等待
            cout << "线程二:缓存区空了,等待生产者生产...\n";
            pthread_cond_wait(&cond, &mutex);          
        }
        num-=1;
        cout << "线程二:num = " << num << ", 通知生活者....\n";
        sleep(1);
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t pthread1, pthread2;
    pthread_create(&pthread1, NULL, producer, NULL);
    pthread_create(&pthread2, NULL, consumser, NULL);
    pthread_join(pthread1, NULL);
    pthread_join(pthread2, NULL);
    return 0;
}