std::lock_guard<std::mutex>locker(m_mutex); m_queue.push_back(element); m_NotEmpty.notify_all(); }voidTake(T&result) { std::unique_lock<std::mutex>locker(m_mutex); m_NotEmpty.wait(locker, [this](){cout <<"take wait!"<< endl;return!m_queue.empty(); }); result=m_queue.f...
void func() { std::lock_guard<std::mutex> l(mutx);//局部变量 析构的时候顺便解锁 for (int i = 0; i < 100; i++) { std::cout << i << std::endl; } } int main() { std::thread t1(func); std::thread t2(func); std::thread t3(func); t1.join(); t2.join(); t3....
pop(); return res; } void pop(T &value) { std::lock_guard<std::mutex> lock(m); if (data.empty()) throw empty_stack(); value = data.top(); data.pop(); } bool empty() const { std::lock_guard<std::mutex> lock(m); return data.empty(); } }; ...
上C++17..。同时,不需要类型擦除。模板函数参数推导为我们提供了一个简单的助手: