I need a new pair of eyes on my code because I cannot figure out why the code crashes.
Here is a pretty straight forward block of code for creating a number of threads:
arrayThread = (int*)malloc(NUM_OF_THREADS * sizeof(int));
for (i = 0; i < NUM_OF_THREADS; i++)
{
f_vars.begin_simulations = (int)i*(no_of_simulations / NUM_OF_THREADS);
f_vars.end_simulations = (int)(i+1)*(no_of_simulations / NUM_OF_THREADS)-1;
arrayThread[i] = _beginthreadex(NULL,
0,
functionPtr,
&f_vars,
0,
&ThreadId);
if (arrayThread[i] == NULL)
{
printf("Create Thread %d get failed. Error no: %d", i, GetLastError);
}
}
WaitForMultipleObjects(NUM_OF_THREADS, arrayThread, TRUE, INFINITE);
for (i = 0; i < NUM_OF_THREADS; i++)
{
CloseHandle(arrayThread[i]);
}
Problem:
The code crashes at line "arrayThread[i] = _beginthreadex". But not always. Sometimes it runs till the end. When I debug via "printf" then the probability is very high that the code finishes successfully.
I have not yet seen an error when NUM_OF_THREADS = 2, sometimes when NUM_OF_THREADS = 3 and often, when
NUM_OF_THREADS > 3.
I intentionally didn’t post a longer piece of code in order to keep it simple.
If there is more you need I’ll provide more code. Maybe some issue already jumps at you while reading
this piece?
Thank you!
I have no further idea what to try.
>Solution :
You allocate an array of int (4 bytes in Windows), but _beginthreadex returns a uintptr_t (8 bytes in a 64-bit Windows program).
The documentation suggests you cast the result to a HANDLE so that you can cleanly pass it to WaitForMultipleObjects and CloseHandle.
Adjust the type of arrayThread and the amount of memory allocated accordingly.
HANDLE *threads = malloc( NUM_OF_THREADS * sizeof( HANDLE ) );
uintptr_t h = _beginthreadex( ... )
if ( !h ) {
// Error handling.
}
threads[ i ] = (HANDLE)h;