std::swap(std::thread)

void swap( thread &lhs, thread &rhs ) noexcept;
(C++11 起)

std::thread 特化 std::swap 算法。交换 lhsrhs 的状态。等效地调用 lhs.swap(rhs)

目录

参数

lhs, rhs - 要交换状态的 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

参阅

交换二个 thread 对象
(公开成员函数)

版本历史

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