boost中线程和function的疑问
问题请见代码中的注释
- C/C++ code
#include "stdafx.h"#include <boost//thread.hpp>#include <boost/bind.hpp>#include <boost/function.hpp>#include <iostream>using namespace std;void fun1(){ while(1) { cout << "fun1" << endl; boost::this_thread::sleep(boost::posix_time::millisec(50)); }}void fun2(long l1, long l2){ while(1) { cout << "l1=" << l1 << " l2=" << l2 << endl; boost::this_thread::sleep(boost::posix_time::seconds(1)); }}long fun3(long l1, long l2, long l3){ while(1) { cout << "l1=" << l1 << " l2=" << l2 << " l3=" << l3 << endl; boost::this_thread::sleep(boost::posix_time::seconds(1)); }}long fun4(long l1, long l2, long l3, long l4){ while(1) { cout << "l1=" << l1 << " l2=" << l2 << " l3=" << l3 << " l4=" << l4 << endl; boost::this_thread::sleep(boost::posix_time::seconds(1)); }}int main(int argc, char* argv[]){ boost::thread tr1(fun1); boost::thread tr2(fun2, 1, 2); boost::thread tr3(boost::bind(fun3, 1, 2, 3)); boost::function< void(void)> func4 = boost::bind(fun4, 1, 2, 3, 4); /* 1、为何这里写boost::function< long(long, long, long, long)> func4 = boost::bind(fun4, 1, 2, 3, 4);的时候 * 下面的boost::thread tr4(func4);就无法通过编译?注:我用的VS2008 * 2、上述两种写法有何区别?为何可以写参数模块可以写 void(void) 呢? */ boost::thread tr4(func4); tr1.join(); tr2.join(); tr3.join(); tr4.join(); return 0;}[解决办法]
fun4总共4个参数,在你全绑定在func4中了,那么再调用func4时就不用参数了
func4()就相当于fun4(1,2,3,4)
boost::thread的线程入口是不能有参数的
[解决办法]
bind实现partial function application,通过现有的函数绑定参数制造新的call wrapper,结果对应的签名必然和原来的不同。long(long, long, long, long)被绑定4个参数以后就只剩long(void)了,当然,可以转为void(void)。
线程入口要参数……用支持variadic template实现的C++11的std::thread吧(也有std::bind/std::function可以用)。
[解决办法]
lz先去看看bind的用法
[解决办法]