threads in c++ using classes

Ian McCulloch ianmcc at vaneyk.lorentz.leidenuniv.nl
Mon Mar 11 23:45:12 EST 2002


On Mon, 11 Mar 2002, rohan mitchell wrote:

> Is it possible to to use threads (i am using SDL threads), where the
> function
> being executed is a function in a class? When i try, i get the error:
> no matches converting function 'processPlayerInput' to type 'int
> (*)(void *)'
> candidates are: int
> RealityUndefined::ServerUniverse::processPlayerInput(RealityUndefined:
> :NetworkServerConnection *)
> 
> I don't get these errors when using plain functions outside of a
> class(c style).
> 
> Thanks in advance,
> Rohan
> 

It is not possible to substitute a member function for a plain function.  
If the thread library requires a plain function (and probably all 
underlying thread libs do) then that is what you must give it.

But you usually get something like a void* parameter which you can pass to 
the thread create function, when then gets passed into the thred execution 
function.  The usual C++ way of doing things is to pass a pointer to an 
object as this extra parameter.  eg, for pthreads (sorry, this is the only 
thread lib I know anything about), you would do it like this:

// thread.h

// this is the global function passed to pthead_create - must use "C" 
// calling convention.
extern "C" void* StartPThread(void* arg);

class thread
{
   public:
      run();   // creates a new thread and starts it

   private:
      pthread_t Thread;

      virtual void do_execute() = 0; // this is what gets executed by the 
                                     // override in a derived class
                                     // to execute the theaded code

   friend void* StartPThread(void*);
};

inline
void thread::run()
{
{
   if (int ECode = pthread_create(&Thread, NULL, StartPThread, 
                                  static_cast<void*>(this)) != 0)
   {
      throw thread_error(ECode);
   }
}

// thread.cpp

extern "C"
void* StartPThread(void* arg)
{
   thread* MyThread = static_cast<thread*>(arg);
   return MyThread->do_execute();
}

hth,
Ian McCulloch






More information about the linux mailing list