简体   繁体   中英

Proper way to terminate a thread in c++

I'm learning about multithreading and I wrote this code:

#include <iostream>
#include <mutex>
#include <thread>
#include <string>
#include <chrono>
#include <condition_variable>

int distance = 20;
int distanceCovered = 0;
std::condition_variable cv;
std::mutex mu;

void keep_moving(){
  while(true){
  std::cout << "Distance is: " << distanceCovered << std::endl;
  std::this_thread::sleep_for(std::chrono::milliseconds(1000));
  distanceCovered++;
  if(distanceCovered == distance){
    cv.notify_one();
    std::terminate();
   }
 }
}

void wake_me_up()
{
  std::unique_lock<std::mutex> ul(mu);
  cv.wait( ul, []{ return distanceCovered==distance; });   // protects the lines of code below
  std::cout << "I'm here" << std::endl;
  std::terminate();
}

int main() {
  std::thread driver(keep_moving);
  std::thread wake_me(wake_me_up);
  driver.join();
  wake_me.join();

  system("pause");

  return 0;
}

As you can see thread 'keep_moving' counts from 0-20 in 20 seconds and then notifies the 'wake_me_up' thread which prints "I'm here" and then terminates. After notifying the thread the 'keep_moving' thread also terminates.

Please tell me if I'm terminating the threads in a proper way. When I run this code I get the following message:

terminate called without an active exception
I'm here
terminate called recursively
Aborted

Thank you.

No. The correct (and only correct in standard C++) way to terminate a thread is to return from its thread function.

std::terminate kills your entire process. Even if it only killed the current thread (ie behaved like the Win32 TerminateThread function, which you should never call !), it would not unwind the stack, not call destructors, and thus possibly leave some necessary cleanup unfinished (like releasing mutexes).

std::terminate is meant to be used on a critical failure where your program cannot possibly continue. The message "without an active exception" is because the primary use of terminate is to kill the program if the exception system fails, eg due to a nested exception, so the function by default looks for an active exception and prints information about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM