class count{public://自定義構(gòu)造函數(shù)count(int _id) :id(_id){}//重載調(diào)用操作符void operator ()() {for (int i = 0; i < 3; ++i){boost::mutex::scoped_locklock(io_mutex);std::cout << id << ": "<<i << std::endl;}}private:int id;};//主程序int main(int argc, char* argv[]){boost::thread thrd1(count(10));boost::thread thrd2(count(20));thrd1.join();thrd2.join();return 0;}代碼執(zhí)行后,顯示線程1執(zhí)行計數(shù)三次完再線程2計數(shù)三次如下1:01:11:22:02:12:2示例代碼中調(diào)用操作符的重載operator沒有帶參數(shù),現(xiàn)想稍作修改在定義調(diào)用操作符的重載時帶上一個參數(shù),來控制計數(shù)的個數(shù),如下void operator ()(int upper) {for (int i = 0; i < upper; ++i){boost::mutex::scoped_locklock(io_mutex);std::cout << id << ": "<<i << std::endl;}main函數(shù)部分要怎么修改才能實(shí)現(xiàn)兩個線程先后計數(shù)不同次數(shù)比先1:0到1:4再2:0到2:9這樣子。示例代碼頭文件部分如下#include <iostream>#include <boost/thread/thread.hpp>#include <boost/thread/mutex.hpp>boost::mutex io_mutex;
1 回答

茅侃侃
TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超22個贊
thread thrd1(count(10), 5); thread thrd2(count(20), 10); |
順帶一提, C++11 已有線程庫,無需使用 boost
- 1 回答
- 0 關(guān)注
- 185 瀏覽
添加回答
舉報
0/150
提交
取消