You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于C++ std::async线程异常捕获的疑问

C++并发编程疑问:为何std::async线程被杀死而非抛出异常被捕获

问题代码

#include <exception>
#include <future>
#include <iostream>
#include <list>
using namespace std;

void func1() {
  list<int> l;
  while (true) {
    for (int i = 0; i < 10000000; ++i) {
      l.push_back(i);
    }
    std::cout.put('.').flush();
  }
}

int main() {
  auto f1 = std::async(func1);
  try {
    f1.get();
  } catch (const exception &e) {
    cerr << "Exception: " << e.what() << endl;
  }
}

运行输出

........................................................................................................................................................................................................................................................................................[1]    23219 killed     ./demo

原因解释

你看到的killed提示并非C异常,而是操作系统因内存耗尽触发OOM Killer终止了整个进程,和C异常机制无关,所以主线程的try-catch块无法捕获该情况:

  • func1中的循环会持续向list<int>添加元素,不断占用内存,直到系统可用资源被耗尽。
  • macOS的xnu内核会启动OOM Killer机制,向内存占用过高的进程发送SIGKILL信号直接终止进程,这个操作属于操作系统层面的强制终止,不属于C++标准定义的异常范畴。
  • std::future::get()只能捕获线程函数中主动抛出的C异常,对于操作系统信号导致的进程终止,C异常处理机制完全无法干预。

验证异常捕获逻辑正常

如果在func1中主动抛出C++异常,比如修改代码如下:

void func1() {
  throw std::runtime_error("Thread exception");
}

此时主线程的try-catch块会正常捕获到异常并输出Exception: Thread exception,说明你的异常捕获逻辑本身是正确的。

内容的提问来源于stack exchange,提问作者waltermitty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 01:05:46