C++11多线程(二):std:thread

时间:2021-12-13 21:02:28

参考链接:http://www.cnblogs.com/haippy/p/3236136.html

目录

1.传参

2.move构造

3.其他成员函数



1.传参

#include "stdafx.h"
#include <iostream>
using namespace std; 
#include <thread>
#include <vector>
#include <mutex>

void func1(int num)
{
	cout << "--------------" << endl;
	cout << "thread id " << this_thread::get_id() << endl;
	for (size_t i = 0; i < 5; i++)
	{
		cout << num++ << endl;
		this_thread::sleep_for(chrono::milliseconds(10));
	}
}
void func2(int &num)
{
	cout << "--------------" << endl;
	cout << "thread id " << this_thread::get_id() << endl;
	for (size_t i = 0; i < 5; i++)
	{
		cout << num++ << endl;
		this_thread::sleep_for(chrono::milliseconds(10));
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	int num = 0;
	thread thread1(func1, num);
	thread1.join();
	cout << "----" << endl;
	cout << "after thread1 , num:"<<num << endl;
	thread thread2(func2, ref(num));
	thread2.join();
	cout << "----" << endl;
	cout << "after thread2 , num:" << num << endl;
	cout << "-----end-------" << endl;
	return 0;
}
输出:

--------------
thread id 7484
0
1
2
3
4
----
after thread1 , num:0
--------------
thread id 7404
0
1
2
3
4
----
after thread2 , num:5
-----end-------
请按任意键继续. . .


2.move

move:   thread& operator= (thread&& rhs) noexcept;
move 构造函数,move 构造函数,调用成功之后 rhs不代表任何 thread 执行对象。

void func2(int &num)
{
	cout << "--------------" << endl;
	cout << "thread id " << this_thread::get_id() << endl;
	for (size_t i = 0; i < 5; i++)
	{
		cout << num++ << endl;
		this_thread::sleep_for(chrono::milliseconds(10));
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	int num = 0;
	thread thread2(func2, ref(num));
	thread thread3(move(thread2));//thread3会执行func2,thread2不再是线程
	thread3.join();
	cout <<"num:" <<num << endl;
	cout << "-----end-------" << endl;
	return 0;
}
输出:

--------------
thread id 8760
0
1
2
3
4
num:5
-----end-------
请按任意键继续. . .

3. 其他成员函数

get_id
获取线程 ID。


joinable
检查线程是否可被 join。


join
阻塞主线程,等待子线程结束。当该线程执行完成后才返回。(即等待子线程执行完毕才继续执行主线程)


detach
Detach 线程。当线程主函数执行完之后,线程就结束了,运行时库负责清理与该线程相关的资源。一般join与detach二选一。


swap
Swap 线程 。


native_handle
返回 native handle。


hardware_concurrency [static]
检测硬件并发特性。