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

Ken*_*edy 3 c++ multithreading

我正在学习多线程,我写了这段代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,线程'keep_moving'在20秒内从0-20开始计数,然后通知'wake_me_up'线程打印"我在这里",然后终止.通知线程后,'keep_moving'线程也终止.

如果我以正确的方式终止线程,请告诉我.当我运行此代码时,我收到以下消息:

terminate called without an active exception
I'm here
terminate called recursively
Aborted
Run Code Online (Sandbox Code Playgroud)

谢谢.

Seb*_*edl 16

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

std::terminate杀死你的整个过程.即使它只杀死当前线程(即表现得像Win32 TerminateThread函数,永远不应该调用!),它不会解除堆栈,也不会调用析构函数,因此可能会留下一些未完成的必要清理(如释放互斥锁).

std::terminate意味着用于您的程序无法继续的严重故障.消息"没有活动异常"是因为主要用途terminate是在异常系统失败时终止程序,例如由于嵌套异常,因此该函数默认查找活动异常并打印有关它的信息.

  • @PasserBy是的。你可以做的事。然后,您必须以某种方式停止执行流程。如果愿意,可以调用std :: abort或ExitProcess甚至是exec,但是该过程不能继续进行。好吧,如果您使用的是没有进程的系统,则可以决定进入一个无限的“闪烁警告LED”循环。 (2认同)
  • 只需“返回”即可。 (2认同)