I am trying to understand how exactly async
differs from using threads. On a conceptual level, I thought multithreading was by definition asynchronous, because you are doing context switches between threads for things like I/O.
But it seems that even for instances like single-threaded applications, just adding threads would be the same as using async
. For example:
#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;
}
Why can't I just create a thread to call is_prime
that writes to some variable, and then call join()
before I print that variable? If I can do this, what really is the benefit of using async
? Some specific examples would be very helpful.