2010-03-18 34 views
1

我正在玩C++和pthreads,到目前为止这么好。如果它是静态的,我可以访问一个类成员函数,如果我将“this”作为参数传递给pthread_create,那么我可以访问一个普通的类成员函数,因为C++会这样做。但我的问题是,我想给这个函数一个int,我不知道如何用pthread_create做多个参数。pthreads和C++

回答

6

传递一个结构指针。

struct Arg { 
    MyClass* _this; 
    int  another_arg; 
}; 

... 

Arg* arg = new Arg; 
arg->_this = this; 
arg->another_arg = 12; 
pthread_create(..., arg); 
... 
delete arg; 
+0

我该怎么做,在C++函数的_this?没有? – vincentkriek 2010-03-18 09:35:28

+0

@user:“访问一个普通的类成员函数”。 – kennytm 2010-03-18 09:38:35

+0

我想我不清楚,让pthread_create执行C++函数,他们需要是静态的。如果可能的话,我希望它们不是静态的。 – vincentkriek 2010-03-18 10:02:45

0

你可以尝试升压线程库和使用boost :: bind()的 下面是一个例子,

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; 
};