`

条件变量

 
阅读更多
#include <iostream>
#include <deque>
#include <thread>
#include <mutex>
#include <condition_variable>

std::deque<int> q;
std::mutex mu;
std::condition_variable cond;
int g_count = 5;

void producer() {
    int count = 0;
    while (count < g_count) {
        std::unique_lock<std::mutex> locker(mu);
        q.push_front(++count);
        std::cout << "produce: " << count << std::endl;
        locker.unlock();
        cond.notify_one();  // Notify one waiting thread, if there is one.
        std::this_thread::sleep_for(std::chrono::seconds(1));

    }
}

void consumer() {
    int data = 0;
    while ( data != g_count) {
        std::unique_lock<std::mutex> locker(mu);
        while(q.empty())
            cond.wait(locker); // Unlock mu and wait to be notified
        data = q.back();
        q.pop_back();
        locker.unlock();
        std::cout << "consume: " << data << std::endl;
    }
}
int main() {
    std::thread t1(producer);
    std::thread t2(consumer);
    t1.join();
    t2.join();
    return 0;
}



produce: 1
consume: 1
produce: 2
consume: 2
produce: 3
consume: 3
produce: 4
consume: 4
produce: 5
consume: 5
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics