views:

741

answers:

2

how to use CreateThread() to create threads of functions which are class members.

+9  A: 

You need to create a static method to use as the actual thread start function, and pass a pointer to the instance as the lpParameter argument to CreateThread. That will get passed to the static method, which can cast it to an object pointer and call through to the member function.

class MyClass
{
    static DWORD WINAPI StaticThreadStart(void* Param)
    {
        MyClass* This = (MyClass*) Param;
        return This->ThreadStart();
    }

    DWORD ThreadStart(void)
    {
        // Do stuff
    }

    void startMyThread()
    {
       DWORD ThreadID;
       CreateThread(NULL, 0, StaticThreadStart, (void*) this, 0, &ThreadID);
    }
};
RichieHindle
A: 

I am trying to do the same thing as RichieHindle said. But, I hit on another problem, when you establish a socket(connecting socket), that is same for all the objects for the above class . And when you are accepting a connection sockets will be created separately for every single accept. There by you have to keep a socket as static member. When I tried to do so I got a different error. I can't post it again. Please go to this link

static-member error

prabhakaran