生产者消费者模型(C++11示例)

一个生产者,两个消费者消费数字示例代码

关键知识点

  • std::thread (c++11线程对象)
  • std::unique_lock + std::mutex + std::condition_variable 配套使用
  • 如何停止消费者线程(std::atomic_bool)

示例代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 

std::queue<int> buffer_;
std::mutex mutex_;
std::condition_variable cv_;
std::atomic_bool stop_(false);

void producer() {
    for (int i = 0; i < 10; i++) {
        {
            std::lock_guard<std::mutex> lk(mutex_);
            buffer_.push(i);
        }
        std::cout << "producer produce number " << i << std::endl;
        cv_.notify_one();

        // sleep 100ms
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
}

void consumer(int index) {
    while(!stop_.load()) {
        std::unique_lock<std::mutex> lk(mutex_);
        cv_.wait(lk);
        if (!buffer_.empty()) {
            int tmp = buffer_.front();
            buffer_.pop();
            std::cout << "consumer #" << index << " consume number " << tmp << std::endl;
        }
    }
}

int main() 
{
    std::thread p1(producer);
    std::thread c1(consumer, 1);
    std::thread c2(consumer, 2);

    p1.join();
    stop_.store(true); // 消费者线程退出
    cv_.notify_all(); // 唤醒所有消费者线程,退出cv_阻塞
    c1.join();
    c2.join();

    return 0;
}

输出结果

xufengbao@MacBook-Pro study % g++ test.cpp -std=c++11
xufengbao@MacBook-Pro study % ./a.out                
producer produce number 0
consumer #1 consume number 0
producer produce number 1
consumer #2 consume number 1
producer produce number 2
consumer #1 consume number 2
producer produce number 3
consumer #2 consume number 3
producer produce number 4
consumer #1 consume number 4
producer produce number 5
consumer #2 consume number 5
producer produce number 6
consumer #1 consume number 6
producer produce number 7
consumer #2 consume number 7
producer produce number 8
consumer #1 consume number 8
producer produce number 9
consumer #2 consume number 9

你可能感兴趣的:(c++,生产者消费者模型)