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. Besides 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.

 

Rainer D 6 P2 540x540Modernes C++ Mentoring

Be part of my mentoring programs:

 

 

 

 

Do you want to stay informed about my mentoring programs: Subscribe via E-Mail.

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;

 

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(). The promise provides this value. 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, and the participants of the task are the promise and the future. The shared variable res is the child's way of transferring the calculation result to the creator. On the contrary, with the promise and future use of a shared 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. If there is an exception in the child thread, the child and creator threads 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 can only provide values for the creator thread, the promise can 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. Specifically, 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, G Prvulovic, Reinhold Dröge, Abernitzke, Frank Grimm, Sakib, Broeserl, António Pina, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, John Breland, Venkat Nandam, Jose Francisco, Douglas Tinkham, Kuchlong Kuchlong, Robert Blanch, Truels Wissneth, Kris Kafka, Mario Luoni, Friedrich Huber, lennonli, Pramod Tikare Muralidhara, Peter Ware, Daniel Hufschläger, Alessandro Pezzato, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, John Wiederhirn, Yacob Cohen-Arazi, Florian Tischler, Robin Furness, Michael Young, Holger Detering, Bernd Mühlhaus, Matthieu Bolt, Stephen Kelley, Kyle Dean, Tusar Palauri, Dmitry Farberov, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, and Rob North.

 

Thanks, in particular, to Jon Hess, Lakshman, Christian Wittenhorst, Sherhy Pyton, Dendi Suhubdy, Sudhakar Belagurusamy, Richard Sargeant, Rusty Fleming, John Nebel, Mipko, Alicja Kaminska, and Slavko Radman.

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

My special thanks to Tipi.build tipi.build logo

 

My special thanks to Take Up Code TakeUpCode 450 60

 

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.

  • C++ - The Core Language
  • C++ - The Standard Library
  • C++ - Compact
  • C++11 and C++14
  • Concurrency with Modern C++
  • Design Pattern and Architectural Pattern with C++
  • Embedded Programming with Modern C++
  • Generic Programming (Templates) with C++

New

  • Clean Code with Modern C++
  • C++20

Contact Me

Modernes C++,

RainerGrimmDunkelBlauSmall

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
-2 #3 apk games 2016-11-13 16:22
Very energetic post, I enjoyed that a lot. Will there be a
part 2?
Quote
-2 #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
-2 #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
+1 #6 Tarun 2021-02-11 18:54
Clear and Simple Explanation
Quote

Stay Informed about my Mentoring

 

Mentoring

English 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

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

Course: Master Software Design Patterns and Architecture in C++

Subscribe to the newsletter (+ pdf bundle)

All tags

Blog archive

Source Code

Visitors

Today 4898

Yesterday 4550

Week 4898

Month 26572

All 12104781

Currently are 176 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments