swap(std::jthread)
來自 cppreference.com
friend void swap( jthread& lhs, jthread& rhs ) noexcept; |
(C++20 起) | |
為 std::jthread 過載 std::swap 演算法。交換 lhs 和 rhs 的狀態。實際上呼叫 lhs.swap(rhs)。此函式對於普通的非限定查詢或限定查詢不可見,只有當 std::jthread 是引數的關聯類時,才能透過實參依賴查詢找到它。
目錄 |
[編輯] 引數
lhs, rhs | - | 要交換狀態的 jthread |
[編輯] 返回值
(無)
[編輯] 示例
執行此程式碼
#include <chrono> #include <iostream> #include <thread> void foo() { std::this_thread::sleep_for(std::chrono::seconds(1)); } void bar() { std::this_thread::sleep_for(std::chrono::seconds(1)); } int main() { using std::swap; std::jthread t1(foo); std::jthread t2(bar); std::cout << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; swap(t1, t2); std::cout << "after std::swap(t1, t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; t1.swap(t2); std::cout << "after t1.swap(t2):" << '\n' << "thread 1 id: " << t1.get_id() << '\n' << "thread 2 id: " << t2.get_id() << '\n'; }
可能的輸出
thread 1 id: 1892 thread 2 id: 2584 after std::swap(t1, t2): thread 1 id: 2584 thread 2 id: 1892 after t1.swap(t2): thread 1 id: 1892 thread 2 id: 2584
[編輯] 另請參見
交換兩個 jthread 物件 (公有成員函式) |