views:

45

answers:

3

Basically I have a class and it is instincable (not static). Basically I want the class to be able to generate its own threads and manage its own stuff. I don't want to make a global callback for each instance I make, this doesnt seem clean and proper to me. What is the proper way of doing what I want. If I try to pass the threadproc to CreateThread and it is the proc from a class instance the compiler says I cannot do this. What is the best way of achieving what I want? Thanks

A: 

What you want to do is create a static member method that in turn calls the threadproc member. It will need a pointer to the class instance to make that call so you will need to pass 'this' as the (void *) parameter to CreateThread.

Amardeep
A: 
class Obj
{
    static ULONG WINAPI ThreadProc(void* p)
    {
       Obj* pThis = (Obj*)p;
       ... do stuff ...
       return 0;
    }

    void StartMemberThread()
    {
         CreateThread(... ThreadProc, this, ... ); 
    }
};

Trickiest part is making sure the thread doesn't use pThis after the object goes away.

DougN
A: 

Why use WIN32 threads when you can use a simple and cross-platform solution such as the boost::thread library? That eliminates your problem altogether. If you are using WIN32 (or pthreads), though, you can specify a void* argument that should be passed to your thread routine. So, that void* object can be a pointer to a class; simply cast it back to its correct type in the thread routine. Once you have casted the void* back to a typed pointer, you can invoke the member functions of that object.

P.S. The word is "instantiable".

Michael Aaron Safyan