简体   繁体   English

在 C++ 中终止线程的正确方法

[英]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.如您所见,线程“keep_moving”在 20 秒内从 0-20 计数,然后通知“wake_me_up”线程,该线程打印“我在这里”然后终止。 After notifying the thread the 'keep_moving' thread also terminates.通知线程后,“keep_moving”线程也终止。

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.不。终止线程的正确(并且仅在标准 C++ 中正确)方法是从其线程函数返回。

std::terminate kills your entire process. std::terminate杀死您的整个过程。 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).即使它只杀死了当前线程(即表现得像 Win32 TerminateThread函数,永远不应该调用它!),它不会展开堆栈,不会调用析构函数,因此可能会留下一些未完成的必要清理(如释放互斥锁)。

std::terminate is meant to be used on a critical failure where your program cannot possibly continue. std::terminate旨在用于您的程序无法继续的严重故障。 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.消息“没有活动异常”是因为terminate的主要用途是在异常系统失败时terminate程序,例如由于嵌套异常,因此该函数默认查找活动异常并打印有关它的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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