pthread member function of a class with arguments

2019-02-20 15:32发布

问题:

I was successful at attaching a thread to class member using the code on the bottom of this page: http://www.tuxtips.org/?p=5.

I can't figure out how to expand the code to encapsulate a method such as void* atom(void *inst) where *inst is a structure that contains various thread parameters. Specifically neither Netbeans nor I understand where the example::*f is defined and how it can be valid in the thread_maker scope.

回答1:

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.