Re: How to use CreateProcess for multiple processes?
Ami wrote:
Hi All,
I have a master application which launches the single worker
program with different command-line parameter. I am using
CreateProcess API for launching the application with desired command-
line. Master application launches the given number of process at a
time out of total number of total required process. For example: if
total number of processes to run is 100, master launches only 10 and
when any process out of currently running process finishes, it
launches the next one so overall count of processes at a given time is
always 10.
My problem is to keep the track of multiple instances of worker
program and when any one finishes launch next instantly with different
command-line parameter.
Can any one suggest what should be the best way to solve the problem?
There are a number of best ways from simplistic to elegant. This is a
classic (almost) worker job pool design. You have 100 jobs and 10
workers and you want to keep each work busy until the 100 jobs are
exhausted.
You can fill a bucket of 100 commands.
You can then that 10 threads. Each thread reads from the bucket and
calls CreateProcess. When CreateProcess returns, the read reads the
bucket again and so.
DWORD CALLBACK SlaveThread(void *p)
{
while(Bucket.NotEmpty() {
cmd = Bucket.Fetch()
CreateProcess(... cmd ..)
}
return 0;
}
int main()
{
FillBucket()
// start 10 threads
for (int i = 0; i < 10; i++) {
DWORD tid;
CloseHandle(CreateThread(NULL,
0,
SlaveThread,
NULL, 0, &tid));
}
// wait here until done.
while (1) {
Sleep(100);
if (kbhit() && getch() == 27) { // escape to exit
}
}
}
So its a perpetual motion concept, which stops when the bucket is empty.
The bucket is a simple FIFO (First in, First Out) queue, it can be a
nice class or an array with an index you manage.
However, what is not shown is you need synchronize the bucket. So if
the class has a reader/writer mutex with it, then it will work very
nicely with threads. For this, a simple critical section can be use.
---