std::thread::swap

1
void swap( thread& other );
(since C++11)

Exchanges the underlying handles of two thread objects.

Parameters

other - the thread to swap with

Return value

(none).

Exceptions

noexcept specification:
noexcept

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#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();
}

Possible output:

1
2
3
4
5
6
7
8
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

See also

specializes the std::swap algorithm
(function template)
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.