Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make sure all threads exited

In a win form application, I have an array of threads which are started like this:

bool stop = false;
Thread[] threads = new Thread[10];

for (int i = 0; i < threads.Length; i++)
    threads[i] = new Thread(new ThreadStart(Job));

// How to make sure all threads have exited, when the boolean = false

void Job()
{
    while (!stop)
        // Do something
}

Now if user press STOP, the boolean value for stop will set to true, so threads exit the Job method one after another. How can I make sure all threads are exited?

NOTE: I need traditional threading for my case and TaskLibrary doesn't fit my scenario.

like image 748
Xaqron Avatar asked Jun 09 '11 02:06

Xaqron


People also ask

How do you make sure that all the threads have been completely executed?

Use Thread. join() in your main thread to wait in a blocking fashion for each Thread to complete, or. Check Thread.

How do you exit a thread?

To end the thread, just return from that function. According to this, you can also call thread. exit() , which will throw an exception that will end the thread silently. thread.

How do you end all threads in C++?

The C++11 does not have direct method to terminate the threads. The std::future<void> can be used to the thread, and it should exit when value in future is available. If we want to send a signal to the thread, but does not send the actual value, we can pass void type object.


2 Answers

Use the Join method to check if all threads have stopped.

 foreach (var t in threads)
 {
     t.Join();
 }
like image 116
Richard Schneider Avatar answered Nov 05 '22 18:11

Richard Schneider


Have you thought about using BackgroundWorkers instead? You said "traditional threads"..I'm not exactly sure what you mean so I don't know if this is a valid proposal or not, but here it is anyways in case Join() doesn't solve your problem

BackgroundWorker[] workers = new BackgroundWorker[10];
bool allThreadsDone = false;

// initialize BackgroundWorkers
for (int i = 0; i < 10; i++)
{
        workers[i] = new BackgroundWorker();
        workers[i].WorkerSupportsCancellation = true;
        workers[i].RunWorkerCompleted += 
            new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
        workers[i].DoWork += new DoWorkEventHandler(AlgorithmsUI_DoWork);
        workers[i].RunWorkerAsync();
}

// thread entry point..DoWork is fired when RunWorkerAsync is called
void AlgorithmsUI_DoWork(object sender, DoWorkEventArgs e)
{
      while (!stop)
            // do something        
}

// this event is fired when the BGW finishes execution
private void  worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    bool threadsStillRunning = false;
    foreach (BackgroundWorker worker in workers)
    {
        if (worker.IsBusy)
        {
            threadsStillRunning = true;
            break;
        }
    }
    if (!threadsStillRunning)
        allThreadsDone = true;
} 

protected override OnFormClosing(FormClosingEventArgs e)
{
         if (!allThreadsDone)
         {
              e.Cancel = true;
              MessageaBox.Show("Threads still running!");
         }
}

This should prevent your form from closing if any threads are still running.

like image 38
alexD Avatar answered Nov 05 '22 18:11

alexD