I need to create an unknown number of threads and at the end want to wait for all the created threads to finish their jobs. After searching, I could only get to wait for some known number of created threads using WaitForMultipleObjects(. . .)
which expects pointer to an array of handles of created threads. The following code is an example of the scenario.
#include "stdafx.h"
#include <Windows.h>
#include <time.h>
FILE* fp;
time_t start;
struct mydata{
int a, b;
};
void myFn(mydata* p)
{
fprintf(fp, "a = %d\n", p->a);
fprintf(fp, "b = %d\n", p->b);
delete p;
}
bool condition()
{
if(time(0) - start >= 1)
return false;
return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
start = time(0);
fopen_s(&fp, "outOfExe.txt", "w");
mydata* dataToGive;
int n = 0;
while(condition())
{
n++;
dataToGive = new mydata;
dataToGive->a = 2*n;
dataToGive->b = 4*n;
HANDLE WINAPI handle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)myFn, dataToGive, 0, NULL);
}
}
The solution I could think of is to create an array of size equal to number of cores in CPU and at any given time execute at max of this number of threads. But for this I would require to develop a queuing mechanism etc. Is there some way to wait for all the created threads by the way shown in above example?
int threadCount, a critical section, an event and WaitForSingleObject?
Lock the CS, create your threads, incing the threadCount, then unlock the CS and wait on the event.
In the thread function/method, do your stuff then, at the end, lock the CS, dec the threadCount. If it is then 0, signal the event. Unlock the CS and exit the thread.
No array, no vector, no, (sane), limit on the number of threads.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments