#include <iostream> #include <list> #include <thread> #include <mutex> #include <condition_variable> #include <unistd.h> std::list<int> my_list; std::mutex my_mutex; std::condition_variable my_cond; void add_element(int value) { while (1) { { std::unique_lock<std::mutex> lock(my_mutex); if (my_list.size() < 100) { my_list.push_back(value); } } usleep(10); } } void remove_element() { while (1) { // sleep(1); if (!my_list.empty()) { std::cout << my_list.size(); std::unique_lock<std::mutex> lock(my_mutex); int value = my_list.front(); my_list.pop_front(); std::cout << " Removed: " << value << std::endl; } usleep(1); } } int main() { std::cout << "start" << std::endl; std::thread t1(add_element, 1); // sleep(1); std::thread t2(add_element, 2); std::thread t3(add_element, 3); std::thread t4(remove_element); t1.join(); t2.join(); t3.join(); return 0; }
标签:std,include,lock,list,mutex,多线程,my From: https://www.cnblogs.com/ahuo/p/17685752.html