C++11多线程:如何启动一个“异步任务”,并介绍std::async、std::future函数使用。

系列文章目录



前言

语言:C++11;
介绍
(1)什么是多线程异步任务?
(2)介绍std::async、std::future函数使用;
(3)编写完整的代码案例并附截图。


一、多线程异步任务

1.1 基本概念

线程各执行各的,没有顺序依赖。

  • 线程同步:是多个线程同时访问同一资源,等待资源访问结束,浪费时间,效率不高,例如多个电脑共用一台打印机设备。
  • 线程异步:访问资源时,如果有空闲时间,则可在空闲等待同时访问其他资源,实现多线程机制,一个浏览器可以打开多个使用。

1.2 使用函数介绍

std::async、std::future创建后台并返回值

1.2.1 什么叫“启动一个异步任务”

就是自动创建一个线程并开始执行对应的线程入口函数,它返回一个std::future对象,

1.2.2 std::async

std::async 是个函数模板,用来启动一个异步任务,启动起来一个异步任务之后,它返回一个std::future对象。
我们通过额外向std::async()传递一个参数,该参数类型是std::lasunch类型(枚举类型),来达到一些特殊的目的,如下:

std::future<int> result = std::async(std::launch::deferred | std::launch::async, mythread);
  1. std::launch::deferred:表示线程入口函数调用被延迟到std::future的wait()或者get()函数调用时才执行,那如果wait()或者get()没有被调用,那么线程 会执行吗?没执行。实际上,线程根本就没创建。

std::launch::deferred:延迟调用,并且没有创建新线程,是在主线程中调用的 线程入口函数;

  1. std::launch::async:在调用async函数的时候就开始创建新线程;

async()函数,默认用的就是std::launch::async标记

1.2.3 std::future

std::future是个类模板。这个std::future对象里边就含有线程入口函数所返回的结果(线程返回的结果),我们可以通过调用future对象的成员函数get()来获取结果;

“future”:将来的意思,有人也称呼std::future提供了一种访问异步操作结果的机制,就是说这个结果你可能没有办法马上拿到,但不久的将来。
在线程执行完毕的时候,你就能够拿到结果了,所以大家就这么理解:这个future(对象)里会保存一个值,在将来的某个时刻

(1)等待线程返回
std::future对象的get()成员函数等待线程执行结束并返回结果;
get()函数:不拿到将来的返回值 誓不罢休,不拿到值我就卡在这里等待拿值。

wait()函数:等待线程返回,本身并不返回结果。

二、代码案例

代码如下(示例):

#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <SDKDDKVer.h>
#include <vector>
#include <map>
#include <string>
#include <thread>
#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);
	//std::future<int> result1 = std::async(mythread);
	//创建线程并开始执行,绑定关系;流程并不卡在这里
	cout << "continue...!" << endl;
	int def;
	def = 0;
	cout << result.get() << endl;
	//卡在这里等待mythread()执行完毕,拿到结果
	//cout << result.get() << endl;
	//get()只能调用一次,不能调用多次;

	//result.wait();
	//等待线程返回,本身并不返回结果;
	cout << "I Love China!" << endl;

	return 0;
}

运行截图(示例):

开始等待5秒钟
在这里插入图片描述
5秒钟结束后
在这里插入图片描述


总结

(1)了解多线程异步任务;
(2)了解线程同步和线程异步的区别;
(3)如何创建一个“异步任务”?
(4)C++11 中std::async、std::future函数使用,以及get()函数的使用。

持续更新中…

猜你喜欢

转载自blog.csdn.net/weixin_55491446/article/details/129695136