用std::thread替換實現boost::thread_group


thread_group是boost庫中的線程池類,內部使用的是boost::thread。

隨着C++ 11標准的制定和各大編譯器的新版本的推出(其實主要是VS2012的推出啦……),本着能用標准庫就用標准庫的指導原則,決定把項目中多線程相關的部分代碼從boost::thread遷移到std::thread。

thread的遷移本身很簡單,畢竟stl的很多功能是直接從boost發展而來的,基本上就是改一下頭文件和名稱空間的問題,例外是thread_group,thread_group是boost的組件,但並不是標准庫的組件,所以需要自己實現一下。

說是自己實現,其實就是復制粘貼boost中的代碼啦。但boost中的thread_group使用shared_mutex來進行線程同步,shared_mutex也沒有進入標准庫,所以需要用什么東西來替代一下。shared_mutex沒能進入標准庫的原因就是C++標准化委員會認為目前可行的shared_mutex實現方案在性能上並不合算,不如直接使用mutex,既然如此,就直接用mutex吧。相應的shared_lock也修改成lock_guard,完成。

復制代碼
#include <thread>
#include <mutex>
#include <list>
#include <memory>
namespace std { //兼容boost::thread_group //使用std::thread代替boost::thread,std::mutex代替boost::shared_mutex class thread_group { private: thread_group(thread_group const&); thread_group& operator=(thread_group const&); public: thread_group() {} ~thread_group() { for(auto it=threads.begin(),end=threads.end(); it!=end;++it) { delete *it; } } template<typename F> thread* create_thread(F threadfunc) { lock_guard<mutex> guard(m); auto_ptr<thread> new_thread(new thread(threadfunc)); threads.push_back(new_thread.get()); return new_thread.release(); } void add_thread(thread* thrd) { if(thrd) { lock_guard<mutex> guard(m); threads.push_back(thrd); } } void remove_thread(thread* thrd) { lock_guard<mutex> guard(m); auto it=std::find(threads.begin(),threads.end(),thrd); if(it!=threads.end()) { threads.erase(it); } } void join_all() { lock_guard<mutex> guard(m); for(auto it=threads.begin(),end=threads.end();it!=end;++it) { (*it)->join(); } } size_t size() const { lock_guard<mutex> guard(m); return threads.size(); } private: list<thread*> threads; mutable mutex m; }; }
復制代碼

——其實完全沒意義嘛……


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM