生产者消费者实现

 

生产者消费者实现 —— 信号量实现方式

#include <iostream>
#include <pthread>
#include <semaphore.h>
#include <cstdlib>

using namespace std;

pthread_mutex_t mutex;
sem_t consume, produce;

void* produce(void*) {
    while (1) {
        sem_wait(&consume);
        pthread_mutex_lock(&mutex);
        cout << "A" << " ";
        pthread_mutex_unlock(&mutex);
    }
}

void* consumer(void*) {
    while (1) {
        sem_wait(&produce);
        pthread_mutex_lock(&mutex);
        cout << "B" << endl;
        pthread_mutex_unlock(&mutex);
    }
}

int main() {
    mutex = PTHREAD_MUTEX_INITIALIZER;
    pthread_t condThread, proThread;
    sem_init(&consume, 0, 1);
    sem_init(&produce, 0, 0);
    int ret = pthread_create(&condThread, NULL, consumer, NULL);
    if (ret == -1) {
        std::cout << "error" << std::endl;
        exit(0);
    }
    ret = pthread_create(&proThread, NULL, producer, NULL);
    if (ret == -1) {
        std::cout << "producer create error" << endl;
        exit(0);
    }
       while (1) {}
    return 0;
}

 

生产者消费者实现

上一篇:SSL详解


下一篇:ABAP-ecc后台把内表生成XML作为excel保存到FTP