C++11 多线程std:: async与std::thread的区别

x33g5p2x  于2022-03-06 转载在 其他  
字(2.6k)|赞(0)|评价(0)|浏览(434)

1. std::async与std::thread的区别

std::async()与std::thread()最明显的不同,就是async并不一定创建新的线程

std::thread() 如果系统资源紧张,那么可能创建线程失败,整个程序可能崩溃。

std::thread()创建线程的方式,如果线程返回值,你想拿到这个值也不容易;

std::async()创建异步任务,可能创建也可能不创建线程;并且async调用方式很容易拿到线程入口函数的返回值。

由于系统资源限制:

(1)如果使用std::thread()创建的线程太多,则可能创建线程失败,系统报告异常,崩溃;

(2)如果用std::async,一般就不会报异常崩溃,因为如果系统资源紧张导致无法创建新线程的时候,std::async这种不加额外参数的调用就不会创建新线程,而是后续谁调用了future::get()来请求结果,那么这个异步任务就运行在执行这条get()语句所在的线程上。

(3)如果你强制std::async创建新线程,那么就必须使用std::launch::async,承受的代价就是系统资源紧张时,可能程序崩溃。经验:一个程序里,线程的数量不易超过100-200,与时间片有关,详情参考操作系统。

2.2 std::async参数详谈

参数std::launch::deferred 延迟调用;参数std::launch::async 强制创建一个新线程

  1. 如果你用std::launch::deferred来调用async会怎么样?std::launch::deferred延迟调用,延迟到future对象调用get()或者wait()的时候才执行mythread();如果不调用get()或者wait(),mythread()不会执行。
  2. std::launch::async:强制这个异步任务在新线程上执行,这意味着,系统必须要给我创建出新线程来运行mythread();
  3. std::launch::async |std::launch::deferred      这里这个 |:以为这调用async的行为可能是 创建新线程并立即执行,或者没有创建新线程并且延迟调用result.get()才开始执行任务入口函数,两者居其一。
  4. 不带额外参数;只给一个入口函数名;默认是应该是std::launch::async |std::launch::deferred,和c)效果一致,换句话说,系统会自行决定是异步(创建新线程)还是同步(不创建新线程)方式运行

2.3 std::async不确定问题的解决

不加额外参数的std::async调用问题,让系统自行决定是否创建新的线程。

问题的焦点在于 std::future<int> result = std::async(mythread)写法,这个异步任务到底 有没有被推迟执行。

实例代码如下:

#include<iostream>
#include<thread>
#include<string>
#include<vector>
#include<list>
#include<mutex>
#include<future>
using namespace std;

int mythread() //线程入口函数
{
	cout << "mythread start" << "threadid= " << std::this_thread::get_id() << endl; //打印线程id

	std::chrono::milliseconds dura(5000); //定一个5秒的时间
	std::this_thread::sleep_for(dura);  //休息一定时常

	cout << "mythread end" << "threadid= " << std::this_thread::get_id() << endl; //打印线程id

	return 5;
}
int main()
{
	cout << "main" << "threadid= " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(mythread);//流程并不卡在这里
	cout << "continue....." << endl;

	//枚举类型
	std::future_status status = result.wait_for(std::chrono::seconds(0));//等待一秒
	
	if (status == std::future_status::deferred)
	{
		//线程被延迟执行了,系统资源紧张
		cout << result.get() << endl; //此时采取调用mythread()
	}
	else if (status == std::future_status::timeout)//
	{
		//超时:表示线程还没执行完;我想等待你1秒,希望你返回,你没有返回,那么 status = timeout
		//线程还没执行完
		cout << "超时:表示线程还没执行完!" << endl;
	}
	else if (status == std::future_status::ready)
	{
		//表示线程成功返回
		cout << "线程成功执行完毕,返回!" << endl;
		cout << result.get() << endl;
	}

	cout << "I love China!" << endl;
	return 0;
}

注:该文是C++11并发多线程视频教程笔记,详情学习:https://study.163.com/course/courseMain.htm?courseId=1006067356

相关文章