Tasks

In this lesson, we will see how tasks should be your first choice in the general case of multithreading.

We'll cover the following

Introduction

Tasks were one of the latest additions to the C++11 standard, and they offer a better abstraction than threads.

In addition to threads, C++ has tasks to perform work asynchronously. Tasks need the <future> header. A task will be parameterized with a work package, and it consists of the two associated components: a promise and a future. Both are connected via data channel.

The promise executes the work packages and puts the result in the data channel. The associated future picks up the result. Both communication endpoints can run in separate threads. What is special is that the future can pick up the result at a later time, meaning that the resulting calculation by the promise is independent of the query of the result by the associated future. .

🔑 Regard tasks as data channels between communication endpoints

Tasks behave like data channels between communication endpoints. One endpoint of the data channel is called the promise. The other endpoint of the data channel is called the future. These endpoints can exist in the same or in different threads. The promise puts its result in the data channel. The future waits for it and picks it up.

Get hands-on with 1200+ tech skills courses.