C++11 线程 swap

swap 

Exchanges the underlying handles of two thread 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;
}

运行结果:

发布了257 篇原创文章 · 获赞 22 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/qq_24127015/article/details/104797885