Search code examples
c++multithreadingfunction-pointersbeginthreadex

Calling _beginthreadx with Passing function Pointers


I'm interested to know if it is possible to call _beginthreadex with function pointer that is not known and NOT based on class design. For example:

#include <stdio.h>
#include <process.h>
#include <windows.h>

int myThread(void* data)
{
    printf("ThreadID: %d \n", GetCurrentThreadId());
    return 1;
}

HANDLE callIntThreadFunc(void (*pFunction)(LPVOID), LPVOID pvFuncArgs)
{
    //Expected to fail compilation due to __stcall
    return (HANDLE) _beginthreadex(NULL, NULL, pFunction, (LPVOID) pvFuncArgs, NULL, NULL);
}

int main(int argc, char *argv[])
{
    HANDLE hThread = callIntThreadFunc(myThread, NULL);
    WaitForSingleObject(hThread , INFINITE);

    return 0;
}

I'm aware that _beginthread can work when converting the function (by the following code):

return (HANDLE) _beginthread((void (*)(void*)) pFunction, 0, (LPVOID) pvFuncArgs);

So my question is if it possible to use _beginthreadex in such cases and if so how? Any thoughts will be appreciated.


Solution

  • Found the answer i was looking for - it is doable and its conversion matter as Lois said. The following code make it happen, compile and spread the thread ;-)

    return (HANDLE) _beginthreadex(NULL, NULL,(unsigned (__stdcall*)(void*)) pFunction, pvFuncArgs, NULL, NULL);
    

    Thanks all.