C++创建线程的三种方式

C++创建线程的三种方式

早期的C++并不支持多线程的创建,如果要创建多线程,依赖的是系统提供的一些方法(例如linux的 pthread). 从C++11以后开始,提供了std::thread线程库,因此我们可以创建std::thread类对象的方式来创建线程。创建的方式主要有三种:

创建线程的三种方式:

  • 通过函数指针
  • 通过函数对象
  • 通过lambda函数

使用std::thread类创建对象,必须包含头文件

#include <thread>

创建的形式是

std::thread thobj(<CALL_BACK>)

新线程将在创建新对象后立即启动,并将与启动该线程的线程并行执行传递的回调。而且,任何线程都可以通过在该线程的对象上调用join()函数来等待另一个线程退出。

通过函数指针创建线程

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

void thread_func()
{
	for(int i= 0; i< 10; ++i)
	{
		cout<<" thread thread_func is running..."<< endl;
		std::this_thread::sleep_for(std::chrono::seconds(1));
	}
}

int main()
{
	 thread threadobj(thread_func);
	cout<<"main Thread is running..."<<endl;
	
	threadobj.join();
	cout<<" exit from main Thread"<<endl;

	return 0;
}

需要注意的是, thread threadobj(thread_func), 函数名是不加括号的。

通过函数对象创建线程

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;

class Thread_Test
{
public:
	void operator()()
	{
		for(int i = 0; i < 10; i++)
		{
			cout<<" Thread_Test is running..."<<endl;
			std::this_thread::sleep_for(std::chrono::seconds(1));
		}
	}	
};

int main()
{
	thread threadobj((Thread_Test()));
	cout<<"main Thread is running..."<<endl;
	
	threadobj.join();
	cout<<" exit from main Thread"<<endl;

	return 0;
}

与上面的方法对比,此处对象Thread_Test()是必须要加括号的.关于operator() 函数对象(仿函数)的相关知识不在这里展开。

lambda函数创建线程

#include <iostream>
#include <thread>
#include <chrono>

using namespace std;
int main()
{
	cout<<"main Thread is running..."<<endl;
	thread threadobj([]{
		for (int i = 0; i < 10; i++)
		{
			cout<<"lambda thread is running ..." <<endl;
			::this_thread::sleep_for(::chrono::seconds(1));
		}
	});

	threadobj.join();
	cout<<" exit from main Thread"<<endl;

	return 0;
}
  • 3
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值