C++11 multithreading: how to start an "asynchronous task", and introduce the use of std::async and std::future functions.

Series Article Directory



foreword

Language: C++11;
Introduction
(1) What is a multi-threaded asynchronous task?
(2) Introduce the use of std::async and std::future functions;
(3) Write a complete code case and attach screenshots.


1. Multi-threaded asynchronous task

1.1 Basic concepts

Threads execute their own tasks, and there is no order dependency.

  • Thread synchronization : Multiple threads access the same resource at the same time, waiting for the resource access to end, which wastes time and is not efficient, such as multiple computers sharing a printer device.
  • Thread asynchronous : When accessing resources, if there is free time, you can access other resources at the same time while waiting to achieve multi-threading mechanism, a browser can open multiple uses.

1.2 Introduction to using functions

std::async, std::future create background and return value

1.2.1 What is "starting an asynchronous task"

It is to automatically create a thread and start executing the corresponding thread entry function, which returns an std::futureobject,

1.2.2 std::async

std::asyncIt is 函数模板used for 启动an asynchronous task. After starting an asynchronous task, it returns an std::futureobject.
We pass an additional parameter to std::async(), the parameter type is std::lasunch type (enumeration type), to achieve some special purposes, as follows:

std::future<int> result = std::async(std::launch::deferred | std::launch::async, mythread);
  1. std::launch::deferred: Indicates that the thread entry function call is delayed until the wait() or get() function call of std::future is executed. If wait() or get() is not called, will the thread execute? Not implemented. In fact, the thread is not created at all.

std::launch::deferred: Deferred call, and no new thread is created, it is a thread entry function called in the main thread;

  1. std::launch::async: Start creating a new thread when calling the async function;

The async() function uses the std::launch::async flag by default

1.2.3 std::future

std::futureis one 类模板. This std::future object contains the result returned by the thread entry function (the result returned by the thread), and we can get()obtain the result by calling the member function of the future object;

“future”: The meaning of the future, some people also call std::future provides a mechanism to access the results of asynchronous operations, which means that 结果you may not be able to get it immediately, but in the near future.
When you are in the thread 执行完毕, you can get the result, so everyone understands this: this future (object) will save a value, and at some point in the future

(1) Wait for the thread to return
the member function of the std::future object get()Wait for the thread to finish executing and return the result;
get() function: I will not stop until I get the return value of the future, and I will be stuck here waiting to get the value if I don’t get the value .

wait() function: waits for the thread to return, and does not return the result itself.

2. Code case

The code is as follows (example):

#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;
}

Run the screenshot (example):

start wait 5 seconds
insert image description here
after 5 seconds end
insert image description here


Summarize

(1) Understand multi-threaded asynchronous tasks;
(2) Understand the difference between thread synchronization and thread asynchronous;
(3) How to create an "asynchronous task"?
(4) The use of std::async, std::future functions in C++11, and the use of the get() function.

Continuously updating...

Guess you like

Origin blog.csdn.net/weixin_55491446/article/details/129695136