Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use async to start concurrent tasks in C++

Shulou Source: shulou.com Published: 2022-06-02 05:57:03 09月21日 Update

In this issue, the editor will bring you about how to use async to start concurrent tasks in C++. The article is rich in content and analyzes and describes for you from a professional point of view. I hope you can get something after reading this article.

Reason (reason)

Similar to R.12, which tells you to avoid raw owning pointers, you should also avoid raw threads and raw promises where possible. Use a factory function such as std::async, which handles spawning or reusing a thread without exposing raw threads to your own code.

R.12 tells us to avoid raw ownership pointers, and this rule tells us that raw threads and promise should be avoided if possible. Using factory functions like std::async, it can start and reuse threads without protecting the original thread from external code.

Example (sample)

Int read_value (const std::string& filename)

{

Std::ifstream in (filename)

In.exceptions (std::ifstream::failbit)

Int value

In > > value

Return value

}

Void async_example ()

{

Try {

Std::future F1 = std::async (read_value, "v1.txt")

Std::future f2 = std::async (read_value, "v2.txt")

Std::cout

Tags: Raw threaded code sample task clocked content function object factory schema analysis different successful unfortunate professional small and medium rich in content reason negative Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Linux Shulou Information MariaDB vpn