std::thread 二:互斥量(带超时的互斥量 timed_mutex())

发布时间 2023-06-18 23:07:20作者: 十一的杂文录

 

timed_mutex 、 try_lock_for 、 try_lock_until

 

#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;

            // try_lock_for 和  try_lock_until 的作用是一样的
            std::chrono::microseconds timeOut(100);
            if (m_mutex.try_lock_for(timeOut))
            {
                // 100ms内拿到了锁
                m_num_list.push_back(i);
                m_mutex.unlock();
            }
            else
            {
                std::this_thread::sleep_for(timeOut);
            }

        }
    }

    void outNum()
    {
        int command = 0;
        while (true)
        {
            std::chrono::microseconds timeOut(100);
            if (m_mutex.try_lock_until(std::chrono::steady_clock::now() + timeOut))
            {
                if (m_num_list.empty())
                {
                    m_mutex.unlock();
                    continue;
                }

                command = m_num_list.front();
                m_num_list.pop_front();
                m_mutex.unlock();
                std::cout << "读取到数据了:" << command << std::endl;
            }
            else
            {
                std::this_thread::sleep_for(timeOut);
            }

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

private:
    std::timed_mutex m_mutex;
    std::list<int> m_num_list;
};

int main()
{
    // 创建对象
    A a;
    std::thread t1(&A::inNum, &a);
    std::thread t2(&A::outNum, &a);

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

    return 0;
}