Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I can't pass a pointer to method to the CreateThread function, of course. What should I do?

like image 347
KOLANICH Avatar asked Jun 09 '11 15:06

KOLANICH


2 Answers

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
}
like image 179
DanDan Avatar answered Sep 30 '22 18:09

DanDan


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)

like image 29
Jörgen Sigvardsson Avatar answered Sep 30 '22 19:09

Jörgen Sigvardsson