【发布时间】:2021-03-25 16:09:38
【问题描述】:
我试图了解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 的真正好处是什么?一些具体的例子会很有帮助。
【问题讨论】:
-
您可以创建一个线程,但这并没有为您提供任何与它同步的固有方法。 IE。您还需要一个互斥锁和/或条件变量等,以便知道线程中的计算完成。
std::async会为您解决这个问题。这并不是说它总是正确的选择,但如果您只是想计算一个与“主”代码并行的一次性结果,那肯定很方便。
标签: c++ multithreading stdasync