Tasks
Explore how C++ tasks manage asynchronous operations using promises and futures. Understand their communication model, differences from threads, and usage of std::async, std::packaged_task, and synchronization techniques to handle results and exceptions effectively.
We'll cover the following...
In addition to threads, C++ has tasks to perform work asynchronously. Tasks need the header
🔑 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.
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 can send the exceptions to the ...