I am playing with C++ and pthreads and so far so good. I can access开发者_StackOverflow a class member function if it's static and I've read that I can access a normal class member functions if I pass "this" as an argument with pthread_create, because c++ does this to, under the hood. But my problem is that I want to give an int to that function, and I don't know how to do multiple arguments with pthread_create.
Pass a struct pointer.
struct Arg {
MyClass* _this;
int another_arg;
};
...
Arg* arg = new Arg;
arg->_this = this;
arg->another_arg = 12;
pthread_create(..., arg);
...
delete arg;
you can try boost thread library and use boost::bind() Here's an example,
class MyThread
{
public:
MyThread( /* Your arguments here */) : m_thread(NULL)
{
m_thread = new boost::thread(boost::bind(&MyThread::thread_routine, this));
}
~MyThread()
{
stop();
}
void stop()
{
if (m_thread)
{
m_thread->interrupt();
m_thread->join();
}
}
private:
void thread_routine() {... /* you can access a/b here */}
private:
int a;
int b;
boost::thread *m_thread;
};
精彩评论