线程安全队列
#pragma once //->from https://blog.csdn.net/what951006/article/details/77916490 #include#include #include #include #include #include using namespace std; template class ThreadSafe_Queue { private: mutable mutex m_mut; queue m_queue; condition_variable m_data_cond; public: ThreadSafe_Queue() {} ThreadSafe_Queue(const ThreadSafe_Queue&) = delete; void push(T data) { lock_guard lg(m_mut); m_queue.push(data); m_data_cond.notify_one(); } void WaitPop(T&t) { unique_lock ul(m_mut); m_data_cond.wait(ul, [this] {return !m_queue.empty(); }); t = m_queue.front(); m_queue.pop(); } shared_ptr WaitPop() { unique_lock ul(m_mut); m_data_cond.wait(ul, [this] {return !m_queue.empty(); }); shared_ptr res(make_shared (m_queue.front())); m_queue.pop(); return res; } bool TryPop(T &t) { lock_guard lg(m_mut); if (m_queue.empty()) return false; t = m_queue.front(); m_queue.pop(); return true; } shared_ptr TryPop() { lock_guard lg(m_mut); if (m_queue.empty()) return shared_ptr (); shared_ptr res(make_shared (m_queue.front())); m_queue.pop(); return res; } bool IsEmpty() { lock_guard lg(m_mut); return m_queue.empty(); } };
线程主函数代码
#include "threadSafeQueue.h" using namespace std; ThreadSafe_Queueg_queue; int g_index = 10; void thread_Fuc() { cout << "thread_fuc1 startn"; while (true) { int value = 0; g_queue.WaitPop(value); printf("wait_and_pop done! value=%d thread id:%dn", value, std::this_thread::get_id()); } } void thread_Fuc2() { cout << "thread_fuc2 startn"; while (true) { std::this_thread::sleep_for(std::chrono::milliseconds(500)); //500 ms g_index++; g_queue.push(g_index); } } int main() { thread thd(thread_Fuc); thd.detach(); thread thd2(thread_Fuc2); thd2.detach(); int a; while (cin >> a) { ; } return 0; }
运行结果


![[c++多线程] [c++多线程]](http://www.mshxw.com/aiimages/31/384925.png)
