首页 > 解决方案 > 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什么?一些具体的例子会很有帮助。

标签: c++multithreadingstdasync

解决方案


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.


推荐阅读