tasksEng

Tasks

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.

Threads versus Tasks

This small code example illustrates the difference:

 

Rainer D 6 P2 500x500Modernes C++ Mentoring

Be part of my mentoring programs:

  • "Fundamentals for C++ Professionals" (open)
  • "Design Patterns and Architectural Patterns with C++" (open)
  • "C++20: Get the Details" (open)
  • "Concurrency with Modern C++" (starts March 2024)
  • Do you want to stay informed: Subscribe.

     

    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, 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, Stephen Kelley, Kyle Dean, Tusar Palauri, Juan Dent, George Liao, Daniel Ceperley, Jon T Hess, Stephen Totten, Wolfgang Fütterer, Matthias Grün, Phillip Diekmann, Ben Atakora, Ann Shatoff, Rob North, Bhavith C Achar, Marco Parri Empoli, moon, Philipp Lenk, Hobsbawm, and Charles-Jianye Chen.

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

    My special thanks to Embarcadero
    My special thanks to PVS-Studio
    My special thanks to Tipi.build 
    My special thanks to Take Up Code
    My special thanks to SHAVEDYAKS

    Seminars

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

    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++
    • Clean Code with Modern C++
    • C++20

    Online Seminars (German)

    Contact Me

    Modernes C++ Mentoring,

     

     

    0 replies

    Leave a Reply

    Want to join the discussion?
    Feel free to contribute!

    Leave a Reply

    Your email address will not be published. Required fields are marked *