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 关注
- 111 浏览
添加回答
举报
0/150
提交
取消