Using swap(), either as a standalone method or as function of a thread instance, one can exchange the underlying thread handles of thread objects:
#include <iostream>
#include <thread>
#include <chrono>
void worker() {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
int main() {
std::thread t1(worker);
std::thread t2(worker);
std::cout << "thread 1 id: " << t1.get_id() << "n";
std::cout << "thread 2 id: " << t2.get_id() << "n";
std::swap(t1, t2);
std::cout << "Swapping threads..." << "n";
std::cout << "thread 1 id: " << t1.get_id() << "n";
std::cout << "thread 2 id: " << t2.get_id() << "n";
t1.swap(t2);
std::cout << "Swapping threads..." << "n";
std::cout << "thread 1 id: " << t1.get_id() << "n";
std::cout << "thread 2 id: " << t2.get_id() << "n";
t1.join();
t2.join();
}
The possible output from this code might look like the following:
thread 1 id: 2
thread 2 id: 3
Swapping threads...
thread 1 id: 3
thread 2 id: 2
Swapping threads...
thread 1 id: 2
thread 2 id: 3
The effect of this is that the state of each thread is swapped with that of the other thread, essentially exchanging their identities.