C++11 multithreading: The difference between std::thread creating threads and std::async creating asynchronous tasks, std::async creating asynchronous tasks is not postponed.

Series Article Directory



foreword

(1) thread creates a new thread;
(2) async creates a new asynchronous task;
whether to create a new thread to execute immediately or delay (no new thread is created) to execute
(3) the difference between std::thread and std::async;


1. The difference between thread and async

std::async creates an asynchronous task test code: 2.1 of this chapter
std::async solution to the uncertainty problem test code: 2.2 of this chapter

1.1 New threads and asynchronous tasks

  • std::thread() If system resources are tight, thread creation may fail, and the entire program may crash when std::thread() is executed.
  • std::async() is generally not called creating threads (explaining that async can create threads), we generally call it to create an asynchronous task.

1.2 The most obvious difference between std::async and std::thread is that async sometimes does not create new threads.

  • a) What happens if you call async with std::launch::deferred?

    std::launch::deferred delays the call and does not create a new thread. Mythread() is delayed until the future object calls .get() or .wait(). If get or wait is not called, then this mythread will not will execute.

  • b) std::launch::async: Force this asynchronous task to execute on a new thread, which means that the system must create a new thread for me to run mythread();

  • c) std::launch::async | std::launch::deferred Here this |: means that the behavior of calling async may be
    "create a new thread and execute it immediately" or "no new thread is created and delayed until the call to result.get () to start executing the task entry function, one of the two"

  • d) We do not take additional parameters; we only give an entry function name to an async function;
    in other words: the system will decide whether to run asynchronously (creating a new thread) or synchronously (not creating a new thread). What does self-determination mean? How the system decides whether to
    run asynchronously (creating a new thread) or synchronously (not creating a new thread).

1.3 The difference between std::async and std::thread

std::thread creates a thread. If the system resources are tight and the thread creation fails, the entire program will report an abnormal crash (tempered)

    int mythread(){
    
    return 1;}
	std::thread mytobj(mythread);
	mytobj.join();

std::threadThe way to create a thread, if the thread returns a value, it is not easy for you to get this value;
std::asynccreate an asynchronous task. May or may not create threads. And the async call method can easily get the return value of the thread entry function;

Due to system resource limitations:

  1. If too many threads are created with std::thread, 创建失败the system may report an exception and crash.
  2. If you use std::async, you will generally not report exceptions and will not crash, because if the system resources are tight and new threads cannot be created, std::async calls without additional parameters will not create new threads. But who subsequently calls result.get() to request the result, then this asynchronous task mythread runs on the thread where this get() is executed.

If you force std::async to create a new thread, then you must use
std::launch::async. The price to bear is that when the system resources are tight, the program crashes.

  1. Experience: For a program, the number of threads should not exceed 100-200 , time slice.

1.4 Solving the problem of std::async uncertainty

Is there a new thread created for immediate execution or delayed (without creating a new thread) execution?

Test method:
std::async call without additional parameters, let the system decide whether to create a new thread. The focus of the problem is std::future result = std :: async
(mythread) function .

wait_for

Code reference chapter 2.2

2. How to use

2.1 std::async creates "asynchronous tasks"

#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <vector>
#include <map>
#include <string>
#include <thread>
#include <list>
#include <mutex>
#include <future>
// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。

// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
// WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>
int mythread2()
{
    
    
	cout << "mythread start" << " threadid = " << std::this_thread::get_id() << endl;
	return 1;
}

int main()
{
    
    
	//二:std::async深入谈
	//(2.1)std::async参数详述,async用来创建一个异步任务
	cout << "main start" << " threadid = " << std::this_thread::get_id() << endl;
	//std::future<int> result = std::async(std::launch::deferred, mythread2);	//deferred延迟调用,并且不创建新线程,延迟到future对象调用.get()或者.wait()的时候才执行mythread()
	//std::future<int> result = std::async(std::launch::async, mythread2);
	//std::future<int> result = std::async(std::launch::async | std::launch::deferred, mythread2);
	std::future<int> result = std::async(std::launch::async | std::launch::deferred, mythread2);
	cout << result.get() << endl;
	return 0;
}

2.2 std::async uncertainty solution test code

The code is as follows (example):

#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include <vector>
#include <map>
#include <string>
#include <thread>
#include <list>
#include <mutex>
#include <future>
// 包括 SDKDDKVer.h 将定义可用的最高版本的 Windows 平台。

// 如果要为以前的 Windows 平台生成应用程序,请包括 WinSDKVer.h,并将
// WIN32_WINNT 宏设置为要支持的平台,然后再包括 SDKDDKVer.h。

#include <SDKDDKVer.h>

int mythread3()
{
    
    
	cout << "mythread start" << " threadid = " << std::this_thread::get_id() << endl;

	std::chrono::milliseconds dura(5000);	//1秒 = 1000毫秒,所以5000毫秒 = 5秒
	std::this_thread::sleep_for(dura);		//休息一定的时长

	return 1;
}

int main()
{
    
    
	cout << "main start" << " threadid = " << std::this_thread::get_id() << endl;
	std::future<int> result = std::async(mythread3);	//想判断async到底有没有创建新线程立即执行还是延迟(没创建新线程)执行。

	std::future_status status = result.wait_for(std::chrono::seconds(0));	
	if (status == std::future_status::deferred)
	{
    
    
		//线程被延迟执行了(系统资源紧张了,它给我采用std::launch::deferred策略了)
		cout << result.get() << endl;	//这个时候才去调用了mythread();
	}
	else
	{
    
    
		//任务没有被推迟,已经开始运行了呗,线程被创建了;
		if (status == std::future_status::ready)
		{
    
    
			//线程成功返回
			cout << "线程成功执行完毕并返回!" << endl;
			cout << result.get() << endl;
		}
		else if (status == std::future_status::timeout)
		{
    
    
			//超时线程还没执行完
			cout << "超时线程还没执行完!" << endl;
			cout << result.get() << endl;
		}
	}
	return 0;
}

Run the screenshot:
insert image description here

Summary:
After the asynchronous task is created, it is not postponed.


Summarize

(1) std::async's mandatory creation of asynchronous tasks () is similar to std::thread creating threads, which is prone to system crashes.

std::async(std::launch::async, mythread2);

(2) std::async creates asynchronous tasks without parameters, which will not cause system crashes.

//默认自带的参数
std::async(std::launch::async | std::launch::deferred, mythread2);
std::async(mythread2);

(3) Threads created using std::async without parameters, after the asynchronous task is created, are not postponed.

Guess you like

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