std::jthread::detach
来自cppreference.com
<tbody>
</tbody>
void detach(); |
(C++20 起) | |
从 jthread 对象分离执行线程,允许它独立地持续执行。当该线程退出时将释放其分配的任何资源。
调用 detach 后 *this 不再占有任何线程。
参数
(无)
返回值
(无)
后条件
joinable 为 false。
异常
若 joinable() == false 或出现任何错误则为 std::system_error。
示例
运行此代码
#include <chrono>
#include <iostream>
#include <thread>
void independentThread()
{
std::cout << "启动并发线程。\n";
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "退出并发线程。\n";
}
void threadCaller()
{
std::cout << "启动线程调用方。\n";
std::jthread t(independentThread);
t.detach();
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "退出线程调用方。\n";
}
int main()
{
threadCaller();
std::this_thread::sleep_for(std::chrono::seconds(5));
}
可能的输出:
启动线程调用方。
启动并发线程。
退出线程调用方。
退出并发线程。
引用
- C++23 标准(ISO/IEC 14882:2024):
- 33.4.4.3 Members [thread.jthread.mem]
- C++20 标准(ISO/IEC 14882:2020):
- 32.4.3.2 Members [thread.jthread.mem]
参阅
| 等待线程完成其执行 (公开成员函数) | |
| 检查线程是否可合并,即潜在运行于并行上下文之中 (公开成员函数) | |
thrd_detach 的 C 文档
| |