在处理新的pthread时将对象的instantion作为参数传递

时间:2013-06-10 22:13:41

标签: c++ multithreading pthreads

我可以创建一个pthread并传递这个线程的ID作为通过这种结构处理这个新线程的函数的参数:

 pthread_t thread;
 pthread_create(&thread, NULL,
         someFunction, (void *) fd);
 // And now handle it with this
 void * someFunction(void *threadid) { }

但是,是否还有任何可能性,如何传递一些对象而不是那个threadid? E.g:

MyObject * o = new MyObject();
pthread_t thread;
       /*and now how to pass o as an paramether, 
        *to be able to work with it later in 
        *my void * someFunction(void *threadid) { } ? 
        */

1 个答案:

答案 0 :(得分:3)

您可以创建一个复合对象:

class MyWrapper
{
    public: void* threadId;
    public: MyObject* o;

    public: MyWrapper(void* threadId, MyObject* o)
    {
        this->threadId = threadId;
        this->o = o;
    }
};
...
pthread_create(&thread, NULL, someFunction, new MyWrapper(threadid, o));

功能:

void * someFunction(void *state)
{
     MyWrapper* wrapper = (MyWrapper*)state;
     ...
}