<menu id="w8yyk"><menu id="w8yyk"></menu></menu>
  • <dd id="w8yyk"><nav id="w8yyk"></nav></dd>
    <menu id="w8yyk"></menu>
    <menu id="w8yyk"><code id="w8yyk"></code></menu>
    <menu id="w8yyk"></menu>
    <xmp id="w8yyk">
    <xmp id="w8yyk"><nav id="w8yyk"></nav>
  • 網站首頁 > 物聯資訊 > 技術分享

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

    2016-09-28 00:00:00 廣州睿豐德信息科技有限公司 閱讀
    睿豐德科技 專注RFID識別技術和條碼識別技術與管理軟件的集成項目。質量追溯系統、MES系統、金蝶與條碼系統對接、用友與條碼系統對接

    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; }; }
    復制代碼

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

    RFID管理系統集成商 RFID中間件 條碼系統中間層 物聯網軟件集成
    最近免费观看高清韩国日本大全