c++ - std::async 与线程
问题描述
我试图了解async
与使用线程有什么不同。在概念层面上,我认为多线程在定义上是异步的,因为您正在线程之间为 I/O 之类的事情进行上下文切换。
但似乎即使对于像单线程应用程序这样的实例,只需添加线程与使用async
. 例如:
#include <iostream> // std::cout
#include <future> // std::async, std::future
// a non-optimized way of checking for prime numbers:
bool is_prime (int x) {
std::cout << "Calculating. Please, wait...\n";
for (int i=2; i<x; ++i) if (x%i==0) return false;
return true;
}
int main ()
{
// call is_prime(313222313) asynchronously:
std::future<bool> fut = std::async (is_prime,313222313);
std::cout << "Checking whether 313222313 is prime.\n";
// ...
bool ret = fut.get(); // waits for is_prime to return
if (ret) std::cout << "It is prime!\n";
else std::cout << "It is not prime.\n";
return 0;
}
为什么我不能只创建一个线程来调用is_prime
写入某个变量,然后join()
在打印该变量之前调用?如果我能做到这一点,那么使用的真正好处是async
什么?一些具体的例子会很有帮助。
解决方案
This is not C++ specific, so I try to be a little bit generic. I'm sure there are C++ specific quirks as well.
Generally speaking, yes. You could just create a variable for the output, start a thread, give the address of the variable to the thread and later .join the thread and access the variable after the thread wrote to it. That works. Nothing wrong with it. We did that for many years.
But as the program gets more complicated, this gets more and more messy. More and more thread to keep running, more and more variables to keep in mind when and how to access them safely. Can I print i
here, or do I need to .join a specific thread first? Who knows.
Futures (or Promises or Tasks) and async/await is a pattern many languages use nowadays under those or very similar names. They don't do anything we could not do before, but they make it a lot easier to maintain when the program grows and is no longer this one page example program that everybody can read on one screen.
推荐阅读
- javascript - 为什么对象要重写另一个冻结的对象
- linux - 使用系统调用在程序集中保存 DNS 响应
- powershell - 获取最近 24 小时内创建的 Azure/Msol 用户。或今天
- django - Django APIView中必填字段的错误
- java - Trie 结构中的“charAt(i) - 'a'” 是什么意思?
- azure-application-insights - Azure 日志分析或应用程序见解中的首次错误
- lotus-domino - 计算剩余天数的两个日期/时间字段之间的差异 - Lotus Notes
- python - 如何找出给定的内置张量流函数接受哪些 dtype 张量?
- javascript - 我可以就我的 Youtube-dl npm 项目中出现的这个错误寻求帮助吗
- python - 无法使用 scrapy 从 Reddit 嵌入式提要窗口获取“href”