0

Hi I have the following C++ code,

I have MyThread class in the thread.h file

class MyThread
{ 
    public:
       void start();
       virtual void* task() = 0;
};

I have worker class in the worker.h file

class Worker : public MyThread
{
    virtual ~Worker();
    virtual void* task();   // I have implementation in worker.cpp
};

Have used pthread_create() in the start() in thread.cpp file for creating a thread and I want to make the task() routine defined in the worker.cpp as the start routine . So how can I do that ? What should I pass as the parameter to the start routine in pthread_create ?

I have tried this but it gives an error:

pthread_create(&(this->threadId),&(this->attr),(void *)task,NULL);                        
KillianDS
  • 16,936
  • 4
  • 61
  • 70
Laavaa
  • 575
  • 9
  • 19
  • 1
    Do you really want to use C++11 like your tag suggests? In that case you can dump pthread and use the built-in threads. – KillianDS Oct 23 '12 at 06:51
  • 1
    Pointer to class-member function actually isn't pointer to function. And +1 for built-in threads. – fasked Oct 23 '12 at 06:53
  • @KillianDS, latest official mingw build, as far as I know, build with thread support desibled. – Lol4t0 Oct 23 '12 at 06:56
  • I hope this [this answher](http://stackoverflow.com/questions/5956759/c11-stdthread-inside-a-class-executing-a-function-member-with-thread-initia) helps you. – PaperBirdMaster Oct 23 '12 at 06:59

2 Answers2

2

You can't use member function as a thread function. You can only use free functions or static member functions, but you can pass arbitrary void* argument to that function and you can pass pointer to this as that argument, that allows you to call member function inside that function:

class MyThread
{ 
    public:
       void start();
       virtual void* task() = 0;

       static void * thread_routine(void* pthis)
       {
            MyThread* t = static_cast<MyThread*>(pthis);
            t->task();
            return 0;
       }
};

Then you launch your thread like this

void MyThread::start()
{
    pthread_create(&(this->threadId),&(this->attr),thread_routine, this);
}
Lol4t0
  • 12,444
  • 4
  • 29
  • 65
0

You can't use task() as start routine for the thread because it is a member function instead of a free function, like the expected signature void *(*start_routine)(void*). (also, it doesn't have the pointer to void parameter)

I would just create a wrapper and have it as the start routine, something like this:

void *wrapper(void *data)
{
    Worker worker;
    worker.task();

}
imreal
  • 10,178
  • 2
  • 32
  • 48