Search⌘ K
AI Features

Threads vs. Tasks

Explore the distinctions between threads and tasks in C++ concurrency. Understand how threads communicate via shared variables while tasks use promises and futures with data channels. Learn about synchronization methods like join() and blocking get() calls, exception handling differences, and the proper use of std::async for safer asynchronous execution.

We'll cover the following...

Threads are very different from tasks. Let’s look at ...

C++
// 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 ...