std::thread::swap

void swap( thread& other ) noexcept;
(C++11 起)

互换二个 thread 对象的底层句柄。

目录

参数

other - 要与之交换的 thread

返回值

(无)

示例

#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::thread t1(foo);
    std::thread t2(bar);
 
    std::cout << "thread 1 id: " << t1.get_id() << std::endl;
    std::cout << "thread 2 id: " << t2.get_id() << std::endl;
 
    std::swap(t1, t2);
 
    std::cout << "after std::swap(t1, t2):" << std::endl;
    std::cout << "thread 1 id: " << t1.get_id() << std::endl;
    std::cout << "thread 2 id: " << t2.get_id() << std::endl;
 
    t1.swap(t2);
 
    std::cout << "after t1.swap(t2):" << std::endl;
    std::cout << "thread 1 id: " << t1.get_id() << std::endl;
    std::cout << "thread 2 id: " << t2.get_id() << std::endl;
 
    t1.join();
    t2.join();
}

可能的输出:

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

参阅

特化 std::swap 算法
(函数模板)

版本历史

  • (当前 | 先前 2017年8月25日 (五) 06:19Fruderica讨论 | 贡献. . (1,438字节) (-396). . (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:36P12bot讨论 | 贡献 . . (1,834字节) (-51). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 18:20P12bot讨论 | 贡献 . . (1,885字节) (+241). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:32P12讨论 | 贡献 . . (1,644字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (1,644字节) (+1,644). . (Translated from the English version using Google Translate)