描述
它用於構造線程對象。
聲明
以下是 std::thread::thread 函數的聲明。
thread() noexcept;
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
thread (const thread&) = delete;
thread (thread&& x) noexcept;
C++11
thread() noexcept;
template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);
thread (const thread&) = delete;
thread (thread&& x) noexcept;
參數
fn− 函數指針、成員指針或任何類型的 move-constructible 函數對象。
args...- 傳遞給 fn 調用的參數。
x- 它是一個線程對象。
返回值
空
異常
空
數據競爭
修改 x。
示例
在下麵的例子中解釋了 std::thread::thread 函數。
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
void f1(int n) {
for (int i = 0; i < 5; ++i) {
std::cout << "1st Thread executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n) {
for (int i = 0; i < 5; ++i) {
std::cout << "2nd Thread executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main() {
int n = 0;
std::thread t1;
std::thread t2(f1, n + 1);
std::thread t3(f2, std::ref(n));
std::thread t4(std::move(t3));
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
讓我們編譯並運行上麵的程序,這將產生以下結果 -
1st Thread executing 2nd Thread executing 1st Thread executing 2nd Thread executing 1st Thread executing 2nd Thread executing 1st Thread executing 2nd Thread executing 2nd Thread executing 1st Thread executing Final value of n is 5
相關用法
- C++ Thread get_id()用法及代碼示例
- C++ Thread get_id用法及代碼示例
- C++ Thread joinable用法及代碼示例
- C++ Thread join用法及代碼示例
- C++ Thread hardware_concurrency()用法及代碼示例
- C++ Thread joinable()用法及代碼示例
- C++ Thread detach用法及代碼示例
- C++ unordered_map cbegin用法及代碼示例
- C++ map lower_bound()用法及代碼示例
- C++ Unordered_multimap reserve()用法及代碼示例
- C++ list assign()用法及代碼示例
- C++ std::max()用法及代碼示例
- C++ std::string::push_back()用法及代碼示例
- C++ Array swap()用法及代碼示例
- C++ valarray cos用法及代碼示例
- C++ multimap key_comp()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ Thread Library - Function constructor。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。