Windows streams - how to make a method a stream function in windows?

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

+5
source share
6 answers

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
}
+7
source

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.)

+5
source

Thread, run() start() ( Java Thread). run() - , , Thread, . start() CreateThread, reinterpret_cast void *. Thread threadEntryPoint(), CreateThread. threadEntryPoint() reinterpret_cast Thread *, run() .

, , ( Thread), , Thread, + run(). , . functor.

+4

CreateThread -. - , lpParameter.

+1

CreateThread lpStartAddress DWORD (WINAPI * PTHREAD_START_ROUTINE) (LPVOID lpThreadParameter), -, - . .

+1

CreateThread , , ,

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

void MyThreadProc()
{
}
-1

All Articles