473,545 Members | 2,032 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 30027
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
20325
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
7473
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
7406
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7660
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7813
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...
0
5976
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...
1
5337
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
4949
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
3457
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1888
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.