C++ 執行緒庫 - detach 函式



描述

當執行緒執行完成時返回。

宣告

以下是 std::thread::detach 函式的宣告。

void join();

C++11

void join();

引數

返回值

異常

不丟擲保證 - 從不丟擲異常。

資料競爭

訪問物件。

示例

以下為 std::thread::detach 的示例。

#include <iostream>
#include <chrono>
#include <thread>

void independentThread() {
   std::cout << "Starting thread.\n";
   std::this_thread::sleep_for(std::chrono::seconds(2));
   std::cout << "Exiting previous thread.\n";
}

void threadCaller() {
   std::cout << "Starting thread caller.\n";
   std::thread t(independentThread);
   t.detach();
   std::this_thread::sleep_for(std::chrono::seconds(1));
   std::cout << "Exiting thread caller.\n";
}

int main() {
   threadCaller();
   std::this_thread::sleep_for(std::chrono::seconds(5));
}

輸出應如下所示:

Starting thread caller.
Starting thread.
Exiting thread caller.
Exiting previous thread.
thread.htm
廣告

© . All rights reserved.