pthread member function of a class with arguments

℡╲_俬逩灬. 提交于 2019-12-01 12:03:23
Lalaland

I think a better solution for using things such as pthread(which take c callbacks) is to create a wrapper function so that you can use much easier to manipulate boost::functions instead. This is similar to Using boost::bind() across C code, will it work?.

Then you could solve your problem simply with 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);

The wrapper function would look like this.

void functionWrapper(void* data)
{

   boost::function<void(void)> *func = (boost::function<void(void)>* ) (data);
   (*func)();
   delete(func);
}

While this method may be more work than manually passing in data, it is much more extendable, making it easy to bind anything and pass it to start your thread.

EDIT

One last note: myClassInstance and myStructInstance should be on the heap. If they are on the stack they could get deleted before your thread starts.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!