boost_thread库求教
小弟最近在研究boost thread库
下面是自己写的1个基本的多线程处理事务的模型 跑是基本没问题 但是不懂效率上来讲 合理么
先谢谢各位了
- C/C++ code
#include <iostream>#include <boost/thread.hpp>#include <boost/bind.hpp>#include <list>using namespace std;boost::mutex mutex;class ThreadMgr{public: ThreadMgr(int i) : m_work_flag(true),m_thread_num(i) { m_works.clear(); Start(); } ~ThreadMgr() { m_thread_list.join_all(); } void Stop() { m_work_flag = false; } void AddWork(int i) { m_works.push_back(i); }private: void Start() { for (int i = 0; i < m_thread_num; ++i) { boost::thread* work = new boost::thread(boost::bind(&ThreadMgr::CallThread, this)); m_thread_list.add_thread(work); } } void CallThread() { while (m_work_flag) { int i = 0; // 这里对m_work_flag的判断是为了在关闭按钮触发后及时停止后台的线程 while(m_work_flag && GetWork(i)) { boost::unique_lock<boost::mutex> lock(mutex); cout << "thread[" << boost::this_thread::get_id() << "] is doing work[" << i << "]." << endl; } } } bool GetWork(int& i) { boost::unique_lock<boost::mutex> lock(mutex); if (m_works.empty()) { return false; } i = m_works.front(); m_works.pop_front(); return true; } boost::thread_group m_thread_list; list<int> m_works; bool m_work_flag; int m_thread_num;};int main(){ ThreadMgr* tm = new ThreadMgr(4); for (int i = 1; i < 10; ++i) { tm->AddWork(i); } for (int i = 10; i < 20; ++i) { tm->AddWork(i); } tm->Stop(); // 关闭按钮之类的触发 delete tm; return 0;}
[解决办法]
队列本身就应该封装成线程安全的,在外层控制不好,并且你外层控制的不对
- C/C++ code
void AddWork(int i) { m_works.push_back(i); }