在C ++中终止线程的正确方法 [英] Proper way to terminate a thread in c++

查看:61
本文介绍了在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;
}

如您所见,线程"keep_moving"在20秒内从0到20计数,然后通知"wake_me_up"线程,该线程打印我在这里",然后终止.通知线程后,"keep_moving"线程也终止.

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

谢谢.

推荐答案

否.终止线程的正确方法(并且仅在标准C ++中正确)是从其线程函数返回.

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

std::terminate杀死您的整个过程.即使它只是杀死当前线程(即行为类似于Win32 TerminateThread函数,您应该从不调用!),它也不会释放堆栈,不会调用析构函数,因此可能未完成一些必要的清理工作(例如释放互斥体).

std::terminate kills your entire process. Even if it only killed the current thread (i.e. 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用于在程序可能无法继续执行的严重故障中使用.消息没有活动的异常"是因为terminate的主要用途是在异常系统发生故障(例如,系统崩溃)时终止程序.由于存在嵌套异常,因此该功能默认情况下会查找活动异常并打印有关该异常的信息.

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, e.g. due to a nested exception, so the function by default looks for an active exception and prints information about it.

这篇关于在C ++中终止线程的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆