#include <boost/thread.hpp> #include <iostream> #include <stdio.h> class SpecificWork { private: int p_; public: SpecificWork(int value) : p_(value) { } void operator()() { printf("Value is %d ", p_); } }; int main() { int i = 1; SpecificWork work(i); boost::thread worker(work); worker.join(); }
启动函数对象线程,注意, work(i) i可以是常数也可以是变量,但是假如写成
boost::thread worker(SpecificWork(1)); 就只能是常数了。
而对于函数来说, 就没有上述限制
void hello(int value) { printf("hello %d ", value); } int main() { int i = 1; SpecificWork work(i); boost::thread worker(&hello, i);//ok boost::thread worker(&hello, 1);//ok worker.join(); }
另外,可以用 boost::bind 绑定函数
int main() { int i = 1; SpecificWork work(i); //boost::thread worker(&hello, i); //ok boost::thread worker(boost::bind(&hello, i)); //ok boost::thread worker(boost::bind(&hello, 1)); //ok worker.join(); }
bind 的用法还不是很熟,待填
Reference
[1] http://kelvinh.github.io/blog/2013/12/03/boost-bind-illustrated/
[2] http://blog.csdn.net/zddblog/article/details/19816309