C++11线程之thread

本文详细介绍了C++11中的std::thread,包括如何创建线程、类与线程的关系、参数传递,以及线程的管理如join、detach、joinable和get_id等。此外,还提及了硬件并发线程数的获取。
摘要由CSDN通过智能技术生成

std::thread::thread

thread() noexcept; (1)(since C++11)
thread(thread&& other)noexcept; (2)(since C++11)
template < class Function, class... args >
explicit thread (Function& fn, Args &&... args);
(3)(since C++11)
thread(const thread&)=delete; (4)(since C++11)

构造新的 thread 对象。
(1)默认构造函数。创建一个不代表任何可执行线程的 thread 对象。
(2)move 构造函数。构造一个 thread 对象,该对象会获取 other 表示的线程,该操作不会以任何方式影响被移动线程的执行,它只是传输其处理程序。在此调用后,other 就不再是一个可执行的线程。
(3)创建一个 thread 对象并将其与执行线程关联,新的执行线程调用 Function 并通过 args 传递参数。
(4)线程不可被 copy (没弄明白)

创建线程

#include <iostream>
#include <thread>
using namespace std;
void f1()
{
   
	for (int i = 0; i < 5; i++)
	{
   
		cout << "--------------" << endl;
	}
}
void f2()
{
   
	for (int i = 0; i < 5; i++)
	{
   
		cout << "++++++++++++++" << endl;
	}
}
int main()
{
   
	thread t1;				//t1 is not a thread
	thread t2(f1);			//t2 is a thread
	thread t3(f2);			
	thread t4(move(t3));	//t4 is now running f2(), t3 is no longer is a thread

	t2.join();
	t4.join();

	return 0;
}

类与线程

#include <iostream>
#include <thread>
using namespace std;
class foo {
   
public:
	void bar()
	{
   
		for (int i = 0; i < 5; i++)
		{
   
			cout << "--------------" << endl;
		}
	}
};
class baz {
   
public:
	void operator()()
	{
   
		for (int i = 0; i < 5; i++)
		{
   
			cout << "++++++++++++++" << endl;
		}
	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值