Using arrays to loop through starting multiple threads, pass different parameters, and return handles for WaitForMultipleObjects
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 me开发者_如何学编程mbers 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.
#include <windows.h>
#include <iostream>
#include <vector>
using std::vector;
using std::cout;
using std::endl;
CRITICAL_SECTION cs;
struct ThreadArgs
{
int id;
};
VOID MyThread(void *data)
{
EnterCriticalSection(&cs);
ThreadArgs *args = (ThreadArgs*)data;
cout << args->id << endl;
LeaveCriticalSection(&cs);
}
int main()
{
InitializeCriticalSection(&cs);
vector <HANDLE> T;
DWORD id;
ThreadArgs args[5] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++)
{
T.push_back(CreateThread(0, 0, (LPTHREAD_START_ROUTINE)MyThread, &args[i], 0, &id));
}
WaitForMultipleObjects(5, &T[0], TRUE, INFINITE);
DeleteCriticalSection(&cs);
}
精彩评论