當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Thread join用法及代碼示例


描述

它在線程執行完成後返回。

聲明

以下是 std::thread::join 函數的聲明。

void join();

C++11

void join();

參數

返回值

異常

No-throw guarantee─ 從不拋出異常。

數據競爭

對象被訪問。

示例

在下麵的 std::thread::join 示例中。

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

void foo() {
   std::this_thread::sleep_for(std::chrono::seconds(1));
}

void bar() {
   std::this_thread::sleep_for(std::chrono::seconds(1));
}

int main() {
   std::cout << "starting helper...\n";
   std::thread helper1(foo);

   std::cout << "starting another helper...\n";
   std::thread helper2(bar);

   std::cout << "waiting for helpers to finish..." << std::endl;
   helper1.join();
   helper2.join();

   std::cout << "done!\n";
}

輸出應該是這樣的——

starting helper...
starting another helper...
waiting for helpers to finish...
done!

相關用法


注:本文由純淨天空篩選整理自 C++ Thread Library - Function join。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。