Threads vs Tasks

This lesson highlights the differences between threads and tasks used in C++ for multithreading.

We'll cover the following...

Threads are very different from tasks. Let’s see how by looking at this piece of code first:

Press + to interact
// asyncVersusThread.cpp
#include <future>
#include <thread>
#include <iostream>
int main(){
std::cout << std::endl;
int res;
std::thread t([&]{ res = 2000 + 11; });
t.join();
std::cout << "res: " << res << std::endl;
auto fut= std::async([]{ return 2000 + 11; });
std::cout << "fut.get(): " << fut.get() << std::endl;
std::cout << std::endl;
}

The child thread t and the asynchronous function call std::async to calculate both the sum of 2000 and 11. The creator thread gets the result from its child thread t via the shared variable res and displays it in line 14. The call std::async in line 16 creates the data channel between the sender (promise) and the receiver (future). Following that, the future asks the data channel with fut.get() (line 17) for the result of the calculation; this fut.get call is blocking.

Based on ...