I want to test out using WaitForMultipleObjects, and to do so I want to start multiple threads, using a loop, each passing different ThreadArgs.
(Essentially just an array of five ThreadArgs, and five HANDLEs?)
When I try to create an array of either the struct, or the HANDLE, neither will work and I get the error ‘cannot allocate an array of constant size 0′ for both, and ”initializing’ : cannot convert from ‘HANDLE’ to ‘HANDLE []” for the latter.
Is an array the appropriate way to do this with regards to the struct? (Also, a note – it will have to remain a struct as it will contain six members eventually, I’m just trying to get it working in a simpler form at first, since adding these members should be very straightforward)
And I’d assume an array of Handles is the best way to do this, but how do I go about declaring one?
Thank you!
#include <windows.h>
#include <iostream>
#include <process.h>
struct ThreadArgs
{
int id;
};
ThreadArgs args = {1};
unsigned int __stdcall MyThread(void *data)
{
std::cout << "Hello World!\n";
ThreadArgs *args = (ThreadArgs *) data;
std::cout << (*args).id;
return 2;
}
int main()
{
HANDLE hThread = (HANDLE) _beginthreadex(NULL, 0, MyThread, &args, 0, NULL);
WaitForSingleObject(hThread, INFINITE);
while(true);
}
The above is my code currently.
I was trying to create an array of HANDLEs using –
HANDLE hThread[5];
Edit:
The error is on this line, when it is altered to be an array of HANDLE[5] –
HANDLE hThread[0] = (HANDLE) _beginthreadex(NULL, 0, MyThread, &args, 0, NULL);
You need to use WaitForMultipleObjects and pass it an array of handles to wait for multiple threads to complete. See an example here.