mutex 互斥量的作用是保护共享数据
*:有 lock() 就一定要有 unlock()
#include <iostream> #include <thread> #include <mutex> #include <list> using namespace std; class A { public: void inNum() { for (int i = 0; i < 10000; i++) { m_mutex.lock(); num_list.push_back(i); cout << "正在写:" << i << endl; m_mutex.unlock(); } } void outNum() { for (int i = 0; i < 10000; i++) { if (!num_list.empty()) { m_mutex.lock(); int temp_num = num_list.front(); num_list.pop_front(); cout << "正在读数据,当前数据:" << temp_num << endl; m_mutex.unlock(); } else { cout << "正在读数据,当前数据:为空" << endl; } } } void parintListCount() { cout << "列表中剩余数量:" << num_list.size() << endl; } private: list<int> num_list; mutex m_mutex; // 创建一个互斥量 }; int main() { A a; thread tIn(&A::inNum, &a); thread tOut(&A::outNum, &a); tIn.join(); tOut.join(); a.parintListCount(); return 0; }
标签:std,thread,lock,互斥,unlock,mutex,include From: https://www.cnblogs.com/shiyixirui/p/17489960.html