I cannot pass a pointer to a method of the CreateThread function, of course. What should I do?
If you use a class, then such a pattern 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 thisin the function of creating the thread as user data (_beginthread [ex], CreateThread, etc.)
this
Thread, run() start() ( Java Thread). run() - , , Thread, . start() CreateThread, reinterpret_cast void *. Thread threadEntryPoint(), CreateThread. threadEntryPoint() reinterpret_cast Thread *, run() .
, , ( Thread), , Thread, + run(). , . functor.
CreateThread -. - , lpParameter.
CreateThread lpStartAddress DWORD (WINAPI * PTHREAD_START_ROUTINE) (LPVOID lpThreadParameter), -, - . .
CreateThread , , ,
CreateThread
CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)&MyThreadProc,NULL,NULL,&threadId);
void MyThreadProc() { }