views:

528

answers:

3

Hello,

I want to create a parallel object oriented system in QNX using c++ and threads. How do I do this?

I tried:

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

with function A being a pointer to a function:

void *functionA()
{ //do something
}

However this function only works in C and not C++. How can I make it work in C++?

+2  A: 

See "How do I pass a pointer-to-member-function to a signal handler, X event callback, system call that starts a thread/task, etc?".

In short, you pass a static function (the "trampoline") as the function pointer. You pass "this" as the user-defined parameter. The static function then bounces the call back to the real object.

For example:

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

And you need to ensure that the C++ function has the same calling convention as expected by pthread_create.

Roger Lipscombe
A: 

I think you need to declare functionA as being extern "C" (and give it the correct signature, see the documentation for pthreads on QNX). This function takes as user parameter the this intance:

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);
}
Carl Seleborg
+1  A: 

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++.

Kleist