Tasks

Now that we've learned about threads, let's discuss tasks for asynchronous programming.

In addition to threads, C++ has tasks to perform work asynchronously. Tasks need the header . A task is parameterized with a work package and consists of the two associated components, a promise, and a future. Both are connected via a 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’s special is that the future can pick up the result at a later time. Therefore the calculation of the result by the promise is independent of the query of the result by the associated future.

🔑 Regard tasks as data channels
Tasks behave like data channels. The promise puts its result in the data channel. The future waits for it and picks it up.

widget

Threads versus Tasks

Threads are very different from tasks. For the communication between the creator thread and the created thread, you have to use a shared variable. The task communicates via its data channel, which is implicitly protected. Therefore a task must not use a protection mechanism like a mutex. The creator thread is waiting for its child with the join call. The future fut is using the fut.get() call which is blocking if no result is there.

If an exception happens in the created thread, the created thread terminates and therefore the creator and the whole process. On the contrary, the promise ...