开发者

Windows threads - how to make a method a thread function in windows?

I can't pass a pointer to method t开发者_运维问答o the CreateThread function, of course. What should I do?


If using a class, some pattern like this usually works well:

.h

static UINT __cdecl StaticThreadFunc(LPVOID pParam);
UINT ThreadFunc();

.cpp

// Somewhere you launch the thread
AfxBeginThread(
    StaticThreadFunc,
    this);  

UINT __cdecl CYourClass::StaticThreadFunc(LPVOID pParam)
{
    CYourClass *pYourClass = reinterpret_cast<CYourClass*>(pParam);
    UINT retCode = pYourClass->ThreadFunc();

    return retCode;
}

UINT CYourClass::ThreadFunc()
{ 
    // Do your thing, this thread now has access to all the classes member variables
}


I often do this:

class X {
private:
    static unsigned __stdcall ThreadEntry(void* pUserData) {
        return ((X*)pUserData)->ThreadMain();
    }

    unsigned ThreadMain() {
         ...
    }
};

And then I pass this as user data to the thread creator function (_beginthread[ex], CreateThread, etc)


The most common way is to create a Thread class that has a run() method and a start() method (these names borrowed from the Java Thread class). run() is a pure virtual that you overload in a class derived from Thread to do the actual work. The method start() internally calls CreateThread passing the this pointer via reinterpret_cast to void*. The Thread class has also a threadEntryPoint() static function that you pass to CreateThread. In threadEntryPoint() you do a reinterpret_cast back to Thread* and then call run() on it.

If there's one situation in which you just want a method of another class to be executed on a separated thread (without having to inherit from the Thread class) you can create a Thread-derived class that receives a pair object+method pointers in the constructor, and calls them in run(). To ease things up, make this derived class a template. Also take a look on boost for functor adaptors.


CreateThread won't take a pointer to a member function. You can wrap the member function in a static function which takes the object pointer through lpParameter.


CreateThread's lpStartAddress is of type DWORD (WINAPI *PTHREAD_START_ROUTINE)(LPVOID lpThreadParameter) and this is incompatible with the member function since the member function has an implicit this pointer in its signature. So create a static function and pass the class pointer as the argument to the thread function.


If you are talking about Native CreateThread Method you would probably need to do following

CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&MyThreadProc,NULL,NULL,&threadId);

Where your callback method is defined as

void MyThreadProc()
{
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜