Can't convert argument to finish program

121 views Asked by At

I am working on a class project and trying to use _beginthreadex as part of a multiprocessing project.

This is the trouble spot. I have this function that I call when using _beginthreadex:

DWORD WINAPI threadWork(LPVOID threadNo)
{
    int threadID = *(int*)threadNo;
    for (unsigned int i = 0; i < numberIter; i++)

and I call the function here:

threadIDs[i] = i;
threads[i] = (HANDLE)_beginthreadex(NULL, 0, threadWork, &threadIDs[i], 0, NULL);

but I keep receiving this error:

'uintptr_t _beginthreadex(void *,unsigned int,_beginthreadex_proc_type,void *,unsigned int,unsigned int *)': cannot convert argument 3 from 'DWORD (__cdecl *)(LPVOID)' to '_beginthreadex_proc_type'

I have done a lot of searching on this topic, and am still very confused and cannot find a solution. I tried replacing LPVOID threadNo with void * as per another thread, but that did not solve my issue. I am assuming it is a pointer issue, but I don't know what I am missing.

1

There are 1 answers

2
Remy Lebeau On

_beginthreadex() is part of Microsoft's C library runtime, not the Win32 API. But you are trying to use a Win32-style callback with it (specifically, a ThreadProc callback for CreateThread()).

If you read the _beginthreadex() documentation, it tells you the correct signature to use for your callback:

unsigned ( __stdcall *start_address )( void * )

So, use this instead:

unsigned __stdcall threadWork(void* argument)
{
    int threadNo = *(int*)argument;
    ...
}

threadIDs[i] = i;
threads[i] = (HANDLE)_beginthreadex(NULL, 0, threadWork, &threadIDs[i], 0, NULL);

But, if your goal really is "learning to use the Win 32 API" then use CreateThread() instead:

DWORD WINAPI threadWork(LPVOID lpParameter)
{
    int threadNo = *(int*)lpParameter;
    ...
}

threadIDs[i] = i;
threads[i] = CreateThread(NULL, 0, threadWork, &threadIDs[i], 0, NULL);

That being said, since your question is tagged [c++], you really should use std::thread or std::jthread instead (unless you are stuck using a pre-2011 compiler):

void threadWork(int threadNo)
{
    ...
}

threads[i] = std::thread(threadWork, i);