std::thread 三:条件变量(condition_variable())

 

condition_variable  、  wait   、  notify_one   、  notify_all

 

*:notify_one:通知(唤醒)一个线程
*:notify_all:通知(唤醒)多个线程

 

#include <iostream>
#include <thread>
#include <mutex>
#include <list>
using namespace std;


class A
{
public:
    void inNum()
    {
        for (int i = 0; i < 10000; i++)
        {
            std::cout << "写入一个数据:" << i << std::endl;

            std::unique_lock<std::mutex> m_lock(m_mutex);
            m_num_list.push_back(i);
            m_cond.notify_one();        // 唤醒wait()
        }
    }

    void outNum()
    {
        while (true)
        {
            std::unique_lock<std::mutex> m_lock(m_mutex);

            // wait() 用来等待一个东西
            // 如果第二个参数lambda表达式,返回false,那么wait将解锁互斥量,并阻塞到本行,等到其他线程调用notify_one()成员为止
            // 如果wait()没有第二个参数,那么效果就跟第二个参数返回false的效果一样
            m_cond.wait(m_lock, [this] {
                if (!m_num_list.empty()) { return true; }
                return false;
                });

            int num = m_num_list.front();
            m_num_list.pop_front();
            m_mutex.unlock();        // 提前解锁,让其他线程可以获取到锁,提高效率
            std::cout << "读取到数据了:" << num << std::endl;

            if (num == 9999) { break; }
        }
    }

private:
    std::mutex m_mutex;
    std::list<int> m_num_list;
    std::condition_variable m_cond;        // 生成一个条件变量对象
};

int main()
{
    A a;
    std::thread t1(&A::inNum, &a);
    std::thread t2(&A::outNum, &a);

    t1.join();
    t2.join();

    return 0;
}

 

posted @ 2023-06-18 23:10  十一的杂文录  阅读(49)  评论(0编辑  收藏  举报