代码示例:

#include <iostream>             
#include <thread>         
#include <chrono>      
#include <mutex>
#include <deque>
#include <condition_variable>

std::deque<int> global_deque;
std::mutex global_mutex;
std::condition_variable global_ConditionVar;

// 生产者线程
void Producer()
{
    while (true)
    {
        // 休眠5毫秒
        std::this_thread::sleep_for(std::chrono::milliseconds(5));

        std::unique_lock<std::mutex> lock(global_mutex);
        global_deque.push_front(1);
        std::cout << "生产者生产了数据" << std::endl;
        global_ConditionVar.notify_all();
    }
}

// 消费者线程
void Consumer()
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(global_mutex);

        // 当队列为空时返回false,则一直阻塞在这一行
        global_ConditionVar.wait(lock, [] {return !global_deque.empty(); });
        global_deque.pop_back();

        std::cout << "消费者消费了数据" << std::endl;
        global_ConditionVar.notify_all();
    }
}

int main()
{

    std::thread consumer_Thread(Consumer);
    //std::thread consumer_Thread1(Consumer);

    std::thread producer_Thread(Producer);

    consumer_Thread.join();
    //consumer_Thread1.join();
    producer_Thread.join();


    getchar();
    return 0;
}