C ++ 11 threads swap

swap 

Exchanges the underlying handles of two thread objects.

Underlying handle two threads to exchange objects.

// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <mutex>
using namespace std;

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;

	t1.swap(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 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.join();
	t2.join();
    return 0;
}

operation result:

Published 257 original articles · won praise 22 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_24127015/article/details/104797885