Tasks

Contents[Show]

Tasks were one of the latest additions to the C++11 standard. They give you a better abstraction than threads. In the general case, they should be your first choice. 

 Tasks as data channels

tasksEng

Tasks behave like data channels. On one side, the sender sets a value. On the other side, the receiver picks up the value. The sender is called promise, the receiver - future. Or to say it in different words, the sender promises to provide a value, which the receiver can pick up in the future.

A few more details. The sender can provide the value for more than one future. Beside a value, the sender can also provide a notification or an exception. The get call of the future blocks. It means, in case the future calls wait, it must wait until the promise puts the value into the channel.

Tasks are available in three variations. As asynchronous function call with std::async, as simple wrapper for a callable with std::packaged_task and as the explicit pair std::promise and std::future.

The best way to get the differences between threads and tasks is to compare them.

Threads versus Tasks

This small code example illustrates the difference:

int res;
std::thread t([&]{res= 3+4;});
t.join();
std::cout << res << std:::endl;

auto fut=std::async([]{return 3+4;});
std::cout << fut.get() << std::endl;

 

Both the child thread and the promise calculate the sum of 3+4 and return the result. The std::async call generates a data channel with both endpoints fut and std::async. fut is a future, std::async  is a promise. The future gets the value with the call fut.get(). This value is provided by the promise. The future can act at a later point in time.

What are the differences?

TaskThreadCompareEng

The thread needs the <thread> header, the task needs the <future> header. The participants of the threads are the creator thread and the child thread, the participant of the task are the promise and the future. The shared variable res is the child's way to transfer the calculation result to the creator. In opposite, promise and future use a common data channel,  std::async creates the data channel.Using fut.get the future gets the result. Using threads you have to protect the shared variable with a lock. But there is implicitly no possibility of a race condition for the promise and the future. The creator of the threads waits with its t.join call, until its child is done. On the other side, the fut.get call blocks. In case there is an exception in the child thread, the child thread and the creator thread terminate. So in the end the whole program terminates. The promise can deliver an exception to the future. The future has to handle the exception. While the child thread is only able to provide values for the creator thread, the promise is able to send values, exceptions and notifications to the associated future. 

The key difference between threads and tasks is the higher abstraction level of tasks. A task will not automatically generate a thread. To be precise, the C++ runtime decides if a thread should be created. Reasons for the decision are: How heavy is the payload? How many cores are available? How high is the system load?

What's next?

So, that was the fundament for the next posts about tasks. The next one is about std::async.(Proofreader Alexey Elymanov)

 

 

 

Thanks a lot to my Patreon Supporters: Matt Braun, Roman Postanciuc, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, espkk, Louis St-Amour, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Neil Wang, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Tobi Heideman, Daniel Hufschläger, Red Trip, Alexander Schwarz, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Dimitrov Tsvetomir, Leo Goodstadt, Eduardo Velasquez, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Haken Gedek, and Bernd Mühlhaus.

 

Thanks in particular to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, and Rusty Fleming.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Seminars

I'm happy to give online seminars or face-to-face seminars worldwide. Please call me if you have any questions.

Bookable (Online)

German

Standard Seminars (English/German)

Here is a compilation of my standard seminars. These seminars are only meant to give you a first orientation.

New

Contact Me

Modernes C++,

RainerGrimmSmall

Tags: tasks

Comments   

+1 #1 Eduard Sukharev 2016-06-01 07:09
Interesting concept. ES6 has similar concept of promises, but they never mentioned them to be tasks. And the most important for promises is that it inverts the workflow dependency and improve readability.
Quote
-1 #2 APK Download 2016-10-24 08:35
My brother recommended I may like this web site.
He was once entirely right. This post actually made my day.
You can not believe simply how a lot time I had spent for this
information! Thanks!
Quote
-1 #3 apk games 2016-11-13 16:22
Very energetic post, I enjoyed that a lot. Will there be a
part 2?
Quote
-1 #4 APK Download 2016-11-29 23:54
I am in fact pleased to glance at this web site posts
which includes plenty of useful data, thanks for providing such information.
Quote
-1 #5 APK Download 2016-12-10 20:39
Its like you read my mind! You seem to know
a lot about this, like you wrote the book in it or something.
I think that you could do with some pics to drive the message home a little bit,
but other than that, this is excellent blog. A fantastic read.
I'll definitely be back.
Quote
0 #6 Tarun 2021-02-11 18:54
Clear and Simple Explanation
Quote

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Interactive Course: The All-in-One Guide to C++20

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 7597

Yesterday 5977

Week 7597

Month 40975

All 8160121

Currently are 239 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments