我使用本页底部的代码成功将线程附加到类成员:http://www.tuxtips.org/?p=5。
我无法弄清楚如何扩展代码以封装诸如void* atom(void *inst
之类的方法,其中*inst
是包含各种线程参数的结构。具体而言,Netbeans和我都不了解example::*f
的定义位置以及它在thread_maker
范围内的有效性。
答案 0 :(得分:1)
我认为使用诸如pthread(采用c回调)之类的东西的更好的解决方案是创建一个包装函数,这样你就可以更容易地操作boost :: functions。这类似于Using boost::bind() across C code, will it work?。
然后你可以使用boost :: bind
解决你的问题class myClass
{
void atom(myStruct *data); // void return type to keep it similar to other code
// You could change it to a void* return type, but then you would need to change the boost::function declarations
};
boost::function<void(void)> function = boost::bind(&myClass::atom,&myClassInstance,&myStructInstance); //bind your function
boost::function<void(void)>* functionCopy = new boost::function<void(void)> (function); //create a copy on the heap
pthread_t id;
pthread_create(&id,NULL,&functionWrapper,functionCopy);
包装函数看起来像这样。
void functionWrapper(void* data)
{
boost::function<void(void)> *func = (boost::function<void(void)>* ) (data);
(*func)();
delete(func);
}
虽然这种方法可能比手动传入数据更有用,但它更具扩展性,可以很容易地绑定任何东西并传递它来启动你的线程。
修改强>
最后一点:myClassInstance和myStructInstance应该在堆上。如果它们在堆栈中,则可以在线程启动之前删除它们。