class count{public://自定義構造函數count(int _id) :id(_id){}//重載調用操作符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;}代碼執行后,顯示線程1執行計數三次完再線程2計數三次如下1:01:11:22:02:12:2示例代碼中調用操作符的重載operator沒有帶參數,現想稍作修改在定義調用操作符的重載時帶上一個參數,來控制計數的個數,如下void operator ()(int upper) {for (int i = 0; i < upper; ++i){boost::mutex::scoped_locklock(io_mutex);std::cout << id << ": "<<i << std::endl;}main函數部分要怎么修改才能實現兩個線程先后計數不同次數比先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貢獻1842條經驗 獲得超21個贊
thread thrd1(count(10), 5); thread thrd2(count(20), 10); |
順帶一提, C++11 已有線程庫,無需使用 boost
- 1 回答
- 0 關注
- 159 瀏覽
添加回答
舉報
0/150
提交
取消