Wait for Thread normally terminate

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi Guys

There is a couple of threads run on my application.
before I quit the main process, i want to stop all the thread,
and then quit main process.

I have set some flag to stop my thread,
something like

void run()
{
while(!stop){
.....
}
}

but what I want to double-confirm is :

void quit(){
waitfortermation(firstThread);//kind of
waitfortermation(secodThread);//kind of
....
}
Can I implement some function like this?
 
WaitForSingleObject(), the Win32 API call, can be used to wait on a thread
handle (you'll have to get the handle, of course). For multiple threads,
you could also P/Invoke WaitForMultipleObjects().

thread.Join() is the usual way to wait for thread to exit...

Paul T.
 
When I create threads, I try to build in an external termination
system. Usually this consists of a while loop that checks a variable
local to the class. I then also have a variable local to the class
that says if the thread is running.

Example

this.ThreadARunning = true;
while(this.AllowThreadAToRun)
{
//Do stuff here

}
this.ThreadARunning = false;

Now when I want to abort the thread, or cause it to stop executing, I
design the "main" thread function to loop. Stopping mid-execution could
cause alot of data headaches. From outside the thread I can watch the
"ThreadAIsRunning" variable to determine if the thread died.
So using your example code, my code would work like this.

this.AllowThreadAToRun = false;
this.AllowThreadBToRun = false;

while(this.ThreadARunning)
{
Application.DoEvents();
}
while(this.ThreadBRunning)
{
Application.DoEvents();
}

Of course you can expand this as you see fit for error checking,
securing data during the abort, and resetting the system to a known
state. But that is upto you.

I like this method because I can guarantee a clean exiting of the
thread and I know for a fact that any clean up the thread needed to do
has been done.

Hope this helps
 
jeff said:
There is a couple of threads run on my application.
before I quit the main process, i want to stop all the thread,
and then quit main process.

In CF1 I use ManualResetEvent initially set to false,
and run method like this (without cleanup):

void run() {
while (!stop){
...
}
event.Set();
}

and StopThread would be like:

void StopThread() {
stop = true;
event.WaitOne();
}

In CF2 there is no need for Event because you can join a thread:

void StopThread() {
stop = true;
m_Thread.Join();
}

hope this helps,
maxxel
 
Back
Top