0

我想使用 c++ 和线程在 QNX 中创建一个并行的面向对象系统。我该怎么做呢?

我试过了:

pthread_t our_thread_id;
pthread_create(&our_thread_id, NULL, &functionA ,NULL);

函数 A 是指向函数的指针:

void *functionA()
{ //do something
}

但是,此函数仅适用于 C 而不是 C++。我怎样才能使它在 C++ 中工作?

4

3 回答 3

2

请参阅“如何将指向成员函数的指针传递给信号处理程序、X 事件回调、启动线程/任务的系统调用等?” .

简而言之,您传递一个静态函数(“蹦床”)作为函数指针。您将“this”作为用户定义的参数传递。然后静态函数将调用反弹回真实对象。

例如:

class Thread {
public:
    int Create()
    {
        return pthread_create(&m_id, NULL, start_routine_trampoline, this);
    }

protected:
    virtual void *start_routine() = 0;

private:
    static void *start_routine_trampoline(void *p)
    {
        Thread *pThis = (Thread *)p;
        return pThis->start_routine();
    }
};

并且您需要确保 C++ 函数具有与 pthread_create 预期的相同的调用约定。

于 2009-01-07T11:49:39.290 回答
1

Your functionA is not a pointer to a function, it's a function returning a void*. The function is also expected to take a void* as argument. This argument is used to pass a pointer to the data needed in the thread.

If you replace

void* functionA() {

with

void functionA(void* threadData) {

I'd expect it to work in both C and C++.

于 2009-10-30T12:10:51.617 回答
0

我认为您需要声明functionA为存在extern "C"(并给它正确的签名,请参阅QNX 上的 pthreads 文档)。此函数将实例作为用户参数this

extern "C"
{
   void* DoSomethingInAThread(void* pGenericThis)
   {
     YourClass* pThis = reinterpret_cast<YourClass*>(pGenericThis);
     pThis->DoSomethingInAThread();
   }
}

int main()
{
  YourClass* pSomeInstance = new YourClass();
  pthread_t our_thread_id;
  pthread_create(&our_thread_id, NULL, &DoSomethingInAThread, pSomeInstance);
}
于 2009-01-07T11:49:54.377 回答