簡體   English   中英

在 C++ 中終止線程的正確方法

[英]Proper way to terminate a thread in c++

我正在學習多線程,並編寫了以下代碼:

#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”線程也終止。

請告訴我是否以正確的方式終止線程。 當我運行此代碼時,我收到以下消息:

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

謝謝你。

不。終止線程的正確(並且僅在標准 C++ 中正確)方法是從其線程函數返回。

std::terminate殺死您的整個過程。 即使它只殺死了當前線程(即表現得像 Win32 TerminateThread函數,永遠不應該調用它!),它不會展開堆棧,不會調用析構函數,因此可能會留下一些未完成的必要清理(如釋放互斥鎖)。

std::terminate旨在用於您的程序無法繼續的嚴重故障。 消息“沒有活動異常”是因為terminate的主要用途是在異常系統失敗時terminate程序,例如由於嵌套異常,因此該函數默認查找活動異常並打印有關它的信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM