473,545 Members | 1,884 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 30029
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.nos pam>
wrote in message news:uV******** ******@TK2MSFTN GP02.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.nos pam>
wrote in message news:uV******** ******@TK2MSFTN GP02.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.Threadin g. 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
WaitForSingleOb ject 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
WaitForSingleOb ject 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
WaitForSingleOb ject 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.nos pam>
wrote in message news:OK******** ******@TK2MSFTN GP05.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
WaitForSingleOb ject 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.Te xt)
for (int i=0; i<iNoThreads; i++)
{
// create the test process thread
}
// wait for all test "SubmitOrde rs" 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.T ext = null;
tbElapsedTime.R efresh();
DateTime startTime = DateTime.Now;

ThreadStart entrypoint = new ThreadStart(Sub mitOrders);
Thread thread = new Thread(entrypoi nt);
thread.Name = "SubmitOrders01 ";
thread.Start();
thread.Join();

DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
tbElapsedTime.T ext = duration.Hours + ":" + duration.Minute s + ":" +
duration.Second s + ":" + duration.Millis econds;
}
Jun 22 '06 #8
Thirsty Traveler wrote:

"Carl Daniel [VC++ MVP]" <cp************ *************** **@mvps.org.nos pam>
wrote in message news:OK******** ******@TK2MSFTN GP05.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
WaitForSingleOb ject 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.Te xt)
for (int i=0; i<iNoThreads; i++)
{
// create the test process thread
}
// wait for all test "SubmitOrde rs" 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.T ext = null;
tbElapsedTime.R efresh();
DateTime startTime = DateTime.Now;

ThreadStart entrypoint = new ThreadStart(Sub mitOrders);
Thread thread = new Thread(entrypoi nt);
thread.Name = "SubmitOrders01 ";
thread.Start();
thread.Join();

DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
tbElapsedTime.T ext = duration.Hours + ":" + duration.Minute s + ":" +
duration.Second s + ":" + duration.Millis econds;
}


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.T ext = null;
tbElapsedTime.R efresh();
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.T ext = string.Format( "{0}:{1}:{2}:{3 }", duration.Hours,
duration.Minute s, duration.Second s, duration.Millis econds );
}
///

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.Wait All()
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.Wait All() 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.Wait All 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

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

Similar topics

4
3291
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 page appear as built. Is there any way to display a "Please Wait" message that displays as soon as the first javascript begins and disappears...
9
1706
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 processed. This can take time. In the mean time, some of the multiple threads have called GetCache(), but because the cache is being updated, I want them...
7
12126
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 responsive to WM_PAINT messages. I know how to do it in VC++ , but I have no idea how it can be done in C#. Please help!!! Regards, Dave
11
20326
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 wait for all its threads to finish? For example, if I start 20 threads: CustomThreadPool pool = new CustomThreadPool("PetersThreadPool");...
18
50920
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 do? Thanks yal!
12
5245
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 block protecting a resource. Thread 2 and 3 also have a SyncLock block protecting the same resource and after executing some code in their blocks...
9
1795
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 (lo.thrd1.IsAlive || lo.thrd2.IsAlive || lo.thrd3.IsAlive)
5
5573
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 be executed and then continue pinging another certer. The ping_completed function is called on completion of ping by the os and i have no...
2
3455
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 allows a commuter to pass easily while a cash booth creates a wait line. The wait line is expected to wait for the 5th commuter to pass before any...
0
7486
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7932
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7442
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7776
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6001
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4965
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3456
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1032
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
729
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.