1

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

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

但是还有没有可能,如何传递某个对象的实例而不是那个threadid?例如:

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) { } ? 
        */
4

1 回答 1

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;
     ...
}
于 2013-06-10T22:40:39.740 回答