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 this piece of code to see how:
The child thread t and the asynchronous function call std::async are both used to calculate 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 this program, we want to ...