cannot convert 'boost::function<void*(void*)>' to 'void* (*)(void*)'
其实我们可以在中间加上一个proxy的函数来解决
如下,pthread_create需要的为函数指针,而我们需要绑定一些参数,我们就可以创建一个proxy代理函数,代理函数复合pthread_create所需函数的要求,但在代理函数里边执行我们的boost::function对象表示的函数。
#include <iostream> #include <string> #include <thread> #include <boost/format.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/thread.hpp> #define LOG(content) cout<<content<<endl; using namespace std; void* realThreadFunction( int first, int second, void *agrv) { //Do things with first and second string content = (boost:: format( "%1% + %2% = %3%") % first % second % (first + second)).str(); LOG(content); return NULL; } void* proxyThreadFunction( void * agrv) { boost::function< void*(void *)>* threadFunction = reinterpret_cast<boost::function <void*(void *)> *>(agrv); (*threadFunction)(NULL); return NULL; } int main() { int a = 10, b = 20; pthread_t threadId; boost::function< void*(void *)> threadFunction = boost::bind( realThreadFunction, a, b, _1); if (0 == pthread_create(&threadId, NULL, proxyThreadFunction, &threadFunction)) { boost::this_thread::sleep(boost::posix_time:: seconds(5)); pthread_join(threadId, NULL); } else { LOG( "create thread fail.") } return 0; }