473,320 Members | 1,988 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How do I wait until all threads have completed

I would like to create a test harness that simulates multiple concurrent
users executing an individual thread. I would like this to be determined at
runtime when the user specifies the number of desired threads. When this is
kicked off, I would like to wait in the primary thread until all worker
threads have completed and time the result... one problem... I can't figure
out how to wait for all threads to complete prior to updating my timing.

Does anyone know how this could be done?
Jun 22 '06 #1
16 29988
Thirsty Traveler wrote:
I would like to create a test harness that simulates multiple
concurrent users executing an individual thread. I would like this to
be determined at runtime when the user specifies the number of
desired threads. When this is kicked off, I would like to wait in the
primary thread until all worker threads have completed and time the
result... one problem... I can't figure out how to wait for all
threads to complete prior to updating my timing.
Does anyone know how this could be done?


1. Accumulate thread handles for all of the threads that you create.
2. After you've created all of the threads, wait on each of the thread
handles one by one in any order.

When the last wait is completed, all of your threads have terminated.

-cd
Jun 22 '06 #2
How do I wait? Do you have a code snippet?

"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote in message news:uV**************@TK2MSFTNGP02.phx.gbl...
Thirsty Traveler wrote:
I would like to create a test harness that simulates multiple
concurrent users executing an individual thread. I would like this to
be determined at runtime when the user specifies the number of
desired threads. When this is kicked off, I would like to wait in the
primary thread until all worker threads have completed and time the
result... one problem... I can't figure out how to wait for all
threads to complete prior to updating my timing.
Does anyone know how this could be done?


1. Accumulate thread handles for all of the threads that you create.
2. After you've created all of the threads, wait on each of the thread
handles one by one in any order.

When the last wait is completed, all of your threads have terminated.

-cd

Jun 22 '06 #3
Thirsty Traveler wrote:
How do I wait? Do you have a code snippet?

"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote in message news:uV**************@TK2MSFTNGP02.phx.gbl...
Thirsty Traveler wrote:
I would like to create a test harness that simulates multiple
concurrent users executing an individual thread. I would like this to
be determined at runtime when the user specifies the number of
desired threads. When this is kicked off, I would like to wait in the
primary thread until all worker threads have completed and time the
result... one problem... I can't figure out how to wait for all
threads to complete prior to updating my timing.
Does anyone know how this could be done?


1. Accumulate thread handles for all of the threads that you create.
2. After you've created all of the threads, wait on each of the thread
handles one by one in any order.

When the last wait is completed, all of your threads have terminated.

-cd


Hi,

Take a look at the WaitHandle class, in System.Threading. It contains a
static method called WaitAll, and this will block the calling thread until
all the WaitHandle's passed in as the parameter are signalled.

What you'll need to do is create an AutoResetEvent for each thread, and when
a thread completes, call the 'Set' method on the AutoResetEvent.
AutoResetEvent inherits from WaitHandle, so all you do is pass an array of
the AutoResetEvent's into the WaitAll method, and when each and every
AutoResetEvent is signalled (i.e. Set has been called) the thread calling
WaitAll will resume.

Hope this helps,
-- Tom Spink
Jun 22 '06 #4
Tom Spink wrote:
What you'll need to do is create an AutoResetEvent for each thread,
and when a thread completes, call the 'Set' method on the
AutoResetEvent. AutoResetEvent inherits from WaitHandle, so all you
do is pass an array of the AutoResetEvent's into the WaitAll method,
and when each and every AutoResetEvent is signalled (i.e. Set has
been called) the thread calling WaitAll will resume.


No, you don't need to do that - you can wait directly on the Thread itself.
For the .NET Thread object, waiting for the thread to complete is done by
calling the Join member function. Internally that'll end up calling
WaitForSingleObject on the thread handle itself, which becomes signalled
when the thread terminates.

-cd
Jun 22 '06 #5
Carl Daniel [VC++ MVP] wrote:
Tom Spink wrote:
What you'll need to do is create an AutoResetEvent for each thread,
and when a thread completes, call the 'Set' method on the
AutoResetEvent. AutoResetEvent inherits from WaitHandle, so all you
do is pass an array of the AutoResetEvent's into the WaitAll method,
and when each and every AutoResetEvent is signalled (i.e. Set has
been called) the thread calling WaitAll will resume.


No, you don't need to do that - you can wait directly on the Thread
itself. For the .NET Thread object, waiting for the thread to complete is
done by
calling the Join member function. Internally that'll end up calling
WaitForSingleObject on the thread handle itself, which becomes signalled
when the thread terminates.

-cd


This is true, but then you'd need to call 'Join' sequentially on each
running worker thread.

-- Tom Spink
Jun 22 '06 #6
Tom Spink wrote:
Carl Daniel [VC++ MVP] wrote:
Tom Spink wrote:
What you'll need to do is create an AutoResetEvent for each thread,
and when a thread completes, call the 'Set' method on the
AutoResetEvent. AutoResetEvent inherits from WaitHandle, so all you
do is pass an array of the AutoResetEvent's into the WaitAll method,
and when each and every AutoResetEvent is signalled (i.e. Set has
been called) the thread calling WaitAll will resume.


No, you don't need to do that - you can wait directly on the Thread
itself. For the .NET Thread object, waiting for the thread to
complete is done by
calling the Join member function. Internally that'll end up calling
WaitForSingleObject on the thread handle itself, which becomes
signalled when the thread terminates.

-cd


This is true, but then you'd need to call 'Join' sequentially on each
running worker thread.


Yep - which accomplishes the sames thing as WaitAll on a bunch of Event
handles much more efficiently, with fewer opportunities for error and with
fewer resources (since you don't need events).

-cd
Jun 22 '06 #7

"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote in message news:OK**************@TK2MSFTNGP05.phx.gbl...
Tom Spink wrote:
Carl Daniel [VC++ MVP] wrote:
Tom Spink wrote:
What you'll need to do is create an AutoResetEvent for each thread,
and when a thread completes, call the 'Set' method on the
AutoResetEvent. AutoResetEvent inherits from WaitHandle, so all you
do is pass an array of the AutoResetEvent's into the WaitAll method,
and when each and every AutoResetEvent is signalled (i.e. Set has
been called) the thread calling WaitAll will resume.

No, you don't need to do that - you can wait directly on the Thread
itself. For the .NET Thread object, waiting for the thread to
complete is done by
calling the Join member function. Internally that'll end up calling
WaitForSingleObject on the thread handle itself, which becomes
signalled when the thread terminates.

-cd


This is true, but then you'd need to call 'Join' sequentially on each
running worker thread.


Yep - which accomplishes the sames thing as WaitAll on a bunch of Event
handles much more efficiently, with fewer opportunities for error and with
fewer resources (since you don't need events).

-cd


I am getting close... I did get the join to work but this does not seem to
be the best way to go. In addition, I am still unclear as to how to start an
aribitrary number of threads.

I am trying to do something like:

private void btnSubmit_Click(object sender, EventArgs e)
{
int iNoThreads = Convert.ToInt16(tbNoThreads.Text)
for (int i=0; i<iNoThreads; i++)
{
// create the test process thread
}
// wait for all test "SubmitOrders" process threads to complete
// display elapsed time and other metrics
}

private void SubmitOrders()
{
// random order submits
}

So far, I have gotten the code below to work, but it does not allow for the
creation of an arbitrary number of threads.

private void btnSubmit_Click(object sender, EventArgs e)
{
int iNoTxns = Convert.ToInt16(tbNoTxns.Text);
tbElapsedTime.Text = null;
tbElapsedTime.Refresh();
DateTime startTime = DateTime.Now;

ThreadStart entrypoint = new ThreadStart(SubmitOrders);
Thread thread = new Thread(entrypoint);
thread.Name = "SubmitOrders01";
thread.Start();
thread.Join();

DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
tbElapsedTime.Text = duration.Hours + ":" + duration.Minutes + ":" +
duration.Seconds + ":" + duration.Milliseconds;
}
Jun 22 '06 #8
Thirsty Traveler wrote:

"Carl Daniel [VC++ MVP]" <cp*****************************@mvps.org.nospam >
wrote in message news:OK**************@TK2MSFTNGP05.phx.gbl...
Tom Spink wrote:
Carl Daniel [VC++ MVP] wrote:

Tom Spink wrote:
> What you'll need to do is create an AutoResetEvent for each thread,
> and when a thread completes, call the 'Set' method on the
> AutoResetEvent. AutoResetEvent inherits from WaitHandle, so all you
> do is pass an array of the AutoResetEvent's into the WaitAll method,
> and when each and every AutoResetEvent is signalled (i.e. Set has
> been called) the thread calling WaitAll will resume.

No, you don't need to do that - you can wait directly on the Thread
itself. For the .NET Thread object, waiting for the thread to
complete is done by
calling the Join member function. Internally that'll end up calling
WaitForSingleObject on the thread handle itself, which becomes
signalled when the thread terminates.

-cd

This is true, but then you'd need to call 'Join' sequentially on each
running worker thread.


Yep - which accomplishes the sames thing as WaitAll on a bunch of Event
handles much more efficiently, with fewer opportunities for error and
with fewer resources (since you don't need events).

-cd


I am getting close... I did get the join to work but this does not seem to
be the best way to go. In addition, I am still unclear as to how to start
an aribitrary number of threads.

I am trying to do something like:

private void btnSubmit_Click(object sender, EventArgs e)
{
int iNoThreads = Convert.ToInt16(tbNoThreads.Text)
for (int i=0; i<iNoThreads; i++)
{
// create the test process thread
}
// wait for all test "SubmitOrders" process threads to complete
// display elapsed time and other metrics
}

private void SubmitOrders()
{
// random order submits
}

So far, I have gotten the code below to work, but it does not allow for
the creation of an arbitrary number of threads.

private void btnSubmit_Click(object sender, EventArgs e)
{
int iNoTxns = Convert.ToInt16(tbNoTxns.Text);
tbElapsedTime.Text = null;
tbElapsedTime.Refresh();
DateTime startTime = DateTime.Now;

ThreadStart entrypoint = new ThreadStart(SubmitOrders);
Thread thread = new Thread(entrypoint);
thread.Name = "SubmitOrders01";
thread.Start();
thread.Join();

DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
tbElapsedTime.Text = duration.Hours + ":" + duration.Minutes + ":" +
duration.Seconds + ":" + duration.Milliseconds;
}


Hi Thirsty,

Perhaps this is what you're trying to do:

(I also optimised your code slightly <g>)

///
private void btnSubmit_Click ( object sender, EventArgs e )
{
int iNoTxns = int.Parse( tbNoTxns.Text );
tbElapsedTime.Text = null;
tbElapsedTime.Refresh();
DateTime startTime = DateTime.Now;

// Start the threads.
List<Thread> threads = new List<Thread>();
for ( int i = 0; i < iNoTxns; i++ )
{
Thread thread = new Thread( SubmitOrders );
thread.Name = string.Format( "SubmitOrders{0}", i );
thread.Start();
}

// Wait for the threads.
foreach ( Thread thread in threads )
thread.Join();

threads.Clear();

DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
tbElapsedTime.Text = string.Format( "{0}:{1}:{2}:{3}", duration.Hours,
duration.Minutes, duration.Seconds, duration.Milliseconds );
}
///

I've used the Thread.Join() method here to wait for thread completion, but
if it was me, I would use the WaitHandles and the WaitHandle.WaitAll()
method I suggested in my other post, which is specifically designed for
waiting for multiple objects, as opposed to this, which sequentially waits
for each thread to complete.

What do other people think?

Hope this helps,
-- Tom Spink
Jun 22 '06 #9
Tom Spink wrote:
I've used the Thread.Join() method here to wait for thread
completion, but if it was me, I would use the WaitHandles and the
WaitHandle.WaitAll() method I suggested in my other post, which is
specifically designed for waiting for multiple objects, as opposed to
this, which sequentially waits for each thread to complete.

What do other people think?


Joining each thread individually has the advantage of supporting any number
of threads.

Using WaitAll, you can only wait on 64 handles at once. The documentation
for WaitHandle.WaitAll says that on some platforms if you wait on more than
64 handles it will fail. As far as I know, "some platforms" could be
re-written "all current platforms" and it would be equally true.

-cd
Jun 22 '06 #10

Tom Spink wrote:

<snip>
I've used the Thread.Join() method here to wait for thread completion, but
if it was me, I would use the WaitHandles and the WaitHandle.WaitAll()
method I suggested in my other post, which is specifically designed for
waiting for multiple objects, as opposed to this, which sequentially waits
for each thread to complete.

What do other people think?


I would personally use Thread.Join - it's clearer to me what that's
doing, as you don't need any extra concepts (WaitHandles).

Jon

Jun 22 '06 #11
"Tom Spink" <ts****@gmail.com> wrote in message
news:e2**************@TK2MSFTNGP05.phx.gbl...

Hi Thirsty,

Perhaps this is what you're trying to do:

(I also optimised your code slightly <g>)

///
private void btnSubmit_Click ( object sender, EventArgs e )
{
int iNoTxns = int.Parse( tbNoTxns.Text );
tbElapsedTime.Text = null;
tbElapsedTime.Refresh();
DateTime startTime = DateTime.Now;

// Start the threads.
List<Thread> threads = new List<Thread>();
for ( int i = 0; i < iNoTxns; i++ )
{
Thread thread = new Thread( SubmitOrders );
thread.Name = string.Format( "SubmitOrders{0}", i );
thread.Start();
}

// Wait for the threads.
foreach ( Thread thread in threads )
thread.Join();

threads.Clear();

DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
tbElapsedTime.Text = string.Format( "{0}:{1}:{2}:{3}", duration.Hours,
duration.Minutes, duration.Seconds, duration.Milliseconds );
}
///

I've used the Thread.Join() method here to wait for thread completion, but
if it was me, I would use the WaitHandles and the WaitHandle.WaitAll()
method I suggested in my other post, which is specifically designed for
waiting for multiple objects, as opposed to this, which sequentially waits
for each thread to complete.

What do other people think?

Hope this helps,
-- Tom Spink


This is elegant and I like it... especially in that I didn't even consider
using a generic to solve my problem of creating arbitrary numbers of
threads..

However, the Join does not appear to be working. My test program places
orders on a mainframe, which results in an elapsed time of approximately
500ms or so. Using the above code, my timer is showing an elapsed time of
approximately 100ms, which leads me to believe it is not blocking.
Jun 22 '06 #12
I just put a Thread.Sleep(3000) in the worker thread and am still getting
the 100ms elapsed time, so the Join clearly does not appear to be working.
Jun 22 '06 #13
Carl Daniel [VC++ MVP] wrote:
Tom Spink wrote:
I've used the Thread.Join() method here to wait for thread
completion, but if it was me, I would use the WaitHandles and the
WaitHandle.WaitAll() method I suggested in my other post, which is
specifically designed for waiting for multiple objects, as opposed to
this, which sequentially waits for each thread to complete.

What do other people think?
Joining each thread individually has the advantage of supporting any
number of threads.

Using WaitAll, you can only wait on 64 handles at once. The documentation
for WaitHandle.WaitAll says that on some platforms if you wait on more
than
64 handles it will fail. As far as I know, "some platforms" could be
re-written "all current platforms" and it would be equally true.

-cd


Hi Carl,
Using WaitAll, you can only wait on 64 handles at once.


Interesting, I did not know that.

-- Tom Spink
Jun 22 '06 #14
Thirsty Traveler wrote:
I just put a Thread.Sleep(3000) in the worker thread and am still getting
the 100ms elapsed time, so the Join clearly does not appear to be working.


You know why that is... I'm a muppet and forgot to add the thread instance
to the list. O_o

Check this out:

///
for ( int i = 0; i < iNoTxns; i++ )
{
Â* Thread thread = new Thread( SubmitOrders );
Â* thread.Name = string.Format( "SubmitOrders{0}", i );
Â* thread.Start();
threads.Add( thread );
}
///

Notice the 'threads.Add( ... )' I put in there at the end of the for loop.

Whoops!
-- Tom Spink

Jun 22 '06 #15
Tom Spink <ts****@gmail.com> wrote:
I've used the Thread.Join() method here to wait for thread completion, but
if it was me, I would use the WaitHandles and the WaitHandle.WaitAll()
method I suggested in my other post, which is specifically designed for
waiting for multiple objects, as opposed to this, which sequentially waits
for each thread to complete.


You still can't continue until all threads are finished, so it doesn't
matter whether you sequentially wait or use WaitAll(), and thus it
doesn't make sense introducing more synchronization objects that will
need to be cleaned up separately.

WaitAll() makes more sense when you need to acquire two or more
synchronization objects simultaneously, without ordering issues.

-- Barry

--
http://barrkel.blogspot.com/
Jun 22 '06 #16
Barry Kelly wrote:
Tom Spink <ts****@gmail.com> wrote:
I've used the Thread.Join() method here to wait for thread completion,
but if it was me, I would use the WaitHandles and the
WaitHandle.WaitAll() method I suggested in my other post, which is
specifically designed for waiting for multiple objects, as opposed to
this, which sequentially waits for each thread to complete.


You still can't continue until all threads are finished, so it doesn't
matter whether you sequentially wait or use WaitAll(), and thus it
doesn't make sense introducing more synchronization objects that will
need to be cleaned up separately.

WaitAll() makes more sense when you need to acquire two or more
synchronization objects simultaneously, without ordering issues.

-- Barry


Hi Barry,

Good point, I like it. :-)

-- Tom Spink
Jun 22 '06 #17

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Dennis M. Marks | last post by:
I have multiple functions that dynamically build parts of a page. It can take 15-30 seconds for this process to complete. In IE nothing appears until the page is complete. In Netscape parts of the...
9
by: Roger Down | last post by:
Lets say I have a method UpdateCache() called from a single thread. I also have a method GetCache() called from multiple threads. When UpdateCache() is called, the cache updating is being...
7
by: Dave Hardy | last post by:
I have thread t1 . It spawns thread t2. I want to wait in thread t1 until the execution of thread t2 in completed. Bu t I do not want it to be a blocking wait since I want thread t1 to be...
11
by: Peter Kirk | last post by:
Hi there I am looking at using a thread-pool, for example one written by Jon Skeet (http://www.yoda.arachsys.com/csharp/miscutil/). Can anyone tell me if this pool provides the possibility to...
18
by: Coder | last post by:
Howdy everybody! How do I do the following... while (myVary != true){}; Obviously I do not want to use 100% of the processor to stay in this infinite loop till myVar == true. But wait do I...
12
by: Perecli Manole | last post by:
I am having some strange thread synchronization problems that require me to better understand the intricacies of Monitor.Wait/Pulse. I have 3 threads. Thread 1 does a Monitor.Wait in a SyncLock...
9
by: Brett Romero | last post by:
I'd like the main thread to wait until these three threads have completed their task: LoadOjbects lo = new LoadOjbects(); lo.thrd1.Start(); lo.thrd2.Start(); lo.thrd3.Start(); while...
5
by: Deepak | last post by:
I am programing a ping application which pings various centers . I used timer loop and it pings one by one. Now when i finish pinging one center it should wait for the ping_completed function to...
2
by: greyradio | last post by:
I've recently have been given an assignment to do and it seems that notify() does notify() any of the waiting threads. The project entails 10 commuters and two different toll booths. The EZPass booth...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.