c++20 中的 std::jthread 是什么?

What is std::jthread in c++20?

  1. 它比 std::thread 有什么优势?
  2. 它会弃用现有的 std::thread 吗?

std::jthread 就像 std::thread,只是没有笨蛋。看,std::thread 的析构函数将终止程序,如果你没有 join 或事先手动分离它。这导致了大量的错误,因为人们希望它加入破坏。

jthread 解决了这个问题;它默认加入销毁(因此名称:"joining thread")。它还支持一种要求线程停止执行的机制,尽管没有强制执行(又名:你不能另一个线程停止执行)。

目前没有弃用的计划std::thread