troubleshooting Question

Multithreading, WaitForMultipleObjects and Variable Number of Threads

Avatar of jtrades
jtrades asked on
CC++Editors IDEs
11 Comments1 Solution1200 ViewsLast Modified:
I am writing a multithreaded application in C using MSVS 2008.  Normally, to create several threads you would write the following lines of code:

HANDLE hThrds[3];

hThrds[0] = (HANDLE)_beginthreadex (NULL, 0, &ThreadFunction, &params, 0, &threadID);
hThrds[1] = (HANDLE)_beginthreadex (NULL, 0, &ThreadFunction, &params, 0, &threadID);
hThrds[2] = (HANDLE)_beginthreadex (NULL, 0, &ThreadFunction, &params, 0, &threadID);

We would then wait for the threads to finish with the following line of code:

WaitForMultipleObjects (3, hThrds, TRUE, INFINITE);

My question is what do we do if we do not know how many threads we will create till runtime?  For example, suppose we still had the declaration

HANDLE hThrds[3];

But only created one thread.

hThrds[0] = (HANDLE)_beginthreadex (NULL, 0, &ThreadFunction, &params, 0, &threadID);

Then the line

WaitForMultipleObjects (3, hThrds, TRUE, INFINITE);

will return an error since the other two thread handles are invalid.  If I put

WaitForMultipleObjects (1, hThrds, TRUE, INFINITE);

instead (because only one thread was created), this causes an error as well.  Therefore, how can I store the handles to a variable number of threads and then use WaitForMultipleObjects?  Or is there another solution that you might suggest?

FYI - I tried using calloc and malloc to create hThrds dynamically,

hThrds = calloc (3, sizeof (HANDLE));

but this did not work since HANDLE does not have a size.
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 11 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros