原文url:http://www.devx.com/SpecialReports/Article/38883
线程库的用法:
void do_work(); //定义线程执行函数
std::thread t(do_work); //创建新线程
这样的执行就相当于我们定义一个“函数类”(一个实现了‘()’操作符的类)
class do_work
{ public:
void operator()();
int status;
};
do_work dw;
std::thread t(dw);//这里实际调用的是do_work类的拷贝构造函数,新建线程中status变量的修改不会影响到主线程中dw.status的值。
参考下面的代码,了解传值和传引用的区别。
#include <thread> #include <chrono> //秒表 #include <iostream> using namespace std; class do_work { public: do_work():status(0)//ctor { }; void operator()() //重载() 操作符 { for (int i = 0; i < 100; i ++){ this_thread::sleep_for(chrono::milliseconds(10)); status ++; } cout << "sub thread finish" << endl; }; int status; }; void main(){ do_work dw; dw.status = 0; cout << "before sub thread complete " << dw.status << endl; std::thread subThread(dw); // 传值 subThread.join(); cout << "after sub thread complete " << dw.status << endl; dw.status = 0; cout << "before sub thread complete " << dw.status << endl; std::thread subThread2(std::ref(dw)); // 传引用 std::thread subThread2(&dw) //compile fail subThread2.join(); cout << "after sub thread complete " << dw.status << endl; } /* 运行结果 before sub thread complete 0 sub thread finish after sub thread complete 0 before sub thread complete 0 sub thread finish after sub thread complete 100 请按任意键继续. . . */