How to use async to start concurrent tasks in C++
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