Boost thread庫的使用 |
您所在的位置:网站首页 › ff14成双的思念任务 › Boost thread庫的使用 |
概要 通過例項介紹boost thread的使用方式,本文主要由執行緒啟動、interruption機制、執行緒同步、等待執行緒退出、thread group幾個部份組成。 正文 執行緒啟動 執行緒可以從以下三種方式啟動: 第一種用struct結構的operator成員函式啟動: [cpp]view plain copy struct callable }; 這裡略去若干行** callable x; boost::thread t(x); 第二種以非成員函式形式啟動執行緒 [cpp]view plain copy void func( intnp) 這裡略去若干行** boost::thread t(func,123); 第三種以成員函式形式啟動執行緒 [cpp]view plain copy #include 這裡略去若干行** class testbind }; 這裡略去若干行** testbind tb; boost::thread t(boost::bind(&testbind::testfunc,&tb,100)); interruption機制 可以通過thread物件的interrupt函式,通知執行緒,需要interrupt。執行緒執行到interruption point就可以退出。 interruption機制舉例: [cpp]view plain copy #include "stdafx.h" #include #include using namespace std; void f() } } } int_tmain( intargc, _tchar* argv) t.interrupt();告訴t執行緒,現在需要interrupt。boost::this_thread::interruption_requested()可以得到當前執行緒是否有一個interrupt請求。若有interrupt請求,執行緒在執行至interruption點時會結束。boost::this_thread::interruption_point();就是一個interruption point。interruption point有多種形式,較常用的有boost::this_thread::sleep(boost::posix_time::seconds(5));當沒有interrupt請求時,這條語句會讓當前執行緒sleep五秒,若有interrupt requirement執行緒結束。 如何使執行緒在執行到interruption point的時候,不會結束,可以參考下面的例子: [cpp]view plain copy #include "stdafx.h" #include #include using namespace std; void f() } } } } int _tmain( intargc, _tchar* argv) 注意boost::this_thread::disable_interruption 這條語句的使用,它可以使大括號內的interruption point不會中斷當前執行緒。 執行緒同步 boost提供了多種lock導致上手需要較長時間,還是看下面執行緒同步的例子比較簡單,相信在多數應用中足夠: 直接使用boost::mutex的例子 [cpp]view plain copy static boost::mutex g_m; 這裡略去若干行** g_m.lock(); 需要鎖定的** g_m.unlock(); 這裡略去若干行** if(g_m.try_lock()) 這裡略去若干行** 使用lock guard的例子 [cpp]view plain copy #include #include #include #include #include using namespace std; static boost::mutex g_m; void f(string strname) } } int _tmain( intargc, _tchar* argv) t.join(); t2.join(); t3.join(); return 0; } 使用unique lock的例子 [cpp]view plain copy #include #include #include #include #include using namespace std; static boost::mutex g_m; void f(string strname) } cout
} int _tmain( intargc, _tchar* argv) 同lock_guard相比 [1]unique lock中有owns lock成員函式,可判斷,當前有沒有被lock。 [2]在構造unique lock時可以指定boost::defer_lock_t引數推遲鎖定,直到unique lock例項呼叫lock。或採用下面的編碼方式使用: boost::unique_locklock(mut,boost::defer_lock); boost::unique_locklock2(mut2,boost::defer_lock); boost::lock(lock,lock2); [3]它可以和conditoin_variable配合使用。 [4]提供了try lock功能。 如果執行緒之間執行順序上有依賴關係,直接到boost官網中參考條件變數(condition variables)的使用。官閘道器於conditon variables的說明還是容易看懂的。 注意,使用一個不恰當的同步可能消耗掉1/2以上的cpu運算能力。 thread group 執行緒組使用示例,其中f函式在上面的例子已經定義 [cpp]view plain copy int_tmain( intargc, _tchar* argv) 【**: Boost thread庫的使用2009 11 26 kagula 閱讀物件 本文假設讀者有幾下skills 1 在c 中至少使用過一種多執行緒開發庫,有mutex和loc... Boost thread庫的使用閱讀物件 本文假設讀者有幾下skills 1 在c 中至少使用過一種多執行緒開發庫,有mutex和lock的概念。 2 熟悉c 開發,在開發... boost threadboost thread最簡單的使用 pragma comment lib e boost lib libboost thread vc90... |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |