The Special Futures

Contents[Show]

The parent of a thread has to take care of their child. The parent can wait until his child is done or detach himself from his child. But that is not really new. But that will not hold for std::async. The big charm of std::async is, that the parent has not taken care of his child.

Fire and forget

std::async creates special futures. These futures wait in their destructor until the work of the associated promise is done. That is the reason, why the creator has not to take care of their child. But it gets even better. You can execute a std::future as a fire-and-forget job. The by std::async created future will be executed just in place. Because the std::future fut is in this case not bound to a variable, it's not possible to invoke fut.get() or fut.wait() on the future to get the result of the promise.

Maybe, my last sentences were a bit too confusing. So I'll compare an ordinary future with a fire-and-forget future. It is necessary for fire-and-forget futures, that the promise runs in a separate thread to start immediately with its work. This is done by the std::launch::async policy. You can read the details of the launch policy in the post asynchronous function calls.

auto fut= std::async([]{return 2011;});
std::cout << fut.get() << std::endl; /// 2011
  
std::async(std::launch::async,[]{std::cout << "fire and forget" << std::endl;});  // fire and forget
  

The fire-and-forget futures have a bag charm. They will run in place and execute their work package, without the creator taking care of them. The simple example shows the described behavior.

 

// async.cpp

#include <iostream>
#include <future>

int main() {

    std::cout << std::endl;
    std::async([](){std::cout << "fire and forget" << std::endl;});
    std::cout << "main done " << std::endl;
}
  

 

Without further ado, the output.

 async

 

The praise for the behavior is high. Too high.

One after another

The future, that is created by std::async, waits in its destructor until its work is done. Another word for waiting is blocking. The future blocks the progress of the program in its destructor. The becomes obvious, in case you use fire-and-forget futures.

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// blocking.cpp

#include <chrono>
#include <future>
#include <iostream>
#include <thread>

int main(){

  std::cout << std::endl;

  std::async(std::launch::async,[]{
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "first thread" << std::endl;
    });
    
  std::async(std::launch::async,[]{
    std::this_thread::sleep_for(std::chrono::seconds(1));  
    std::cout << "second thread" << std::endl;}
    );
  
  std::cout << "main thread" << std::endl;  

}

 

The program executes two promises in its own thread. The resulting futures are fire-and-forget futures. These futures block in their destructor until the associated promise is done. The result is, that the promise will be executed with high probability in that sequence, in which you find them in the source code. That is exactly what you see in the output of the program.

 

blocking

I want to stress this point once more. Although I create in the main-thread two promises, which are executed in separate threads, the threads run in sequence one after the other. That is the reason, why the thread with the more time-consuming work package (line 12) finishes first. Wow, that was disappointing. Instead of three threads running concurrently, each thread will be executed after another.

The key issue is, that the by std::async created thread is waiting in its destructor until the associated promise is done, which can not be solved. The problem can only be mitigated. In case you bind the future to a variable, the blocking will take place at the time point when the variable goes out of scope. That is the behavior, you can observe in the next example.

  

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// notBlocking.cpp

#include <chrono>
#include <future>
#include <iostream>
#include <thread>

int main(){

  std::cout << std::endl;

  auto first= std::async(std::launch::async,[]{
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "first thread" << std::endl;
    });
    
  auto second= std::async(std::launch::async,[]{
    std::this_thread::sleep_for(std::chrono::seconds(1));  
    std::cout << "second thread" << std::endl;}
    );
  
  std::cout << "main thread" << std::endl;  

}

 

Now, the output of the program matches our intuition, because the three threads are executed in parallel. The future first (line 12) and second (line 17) are valid until the end of the main function (line 24). So, the destructor will perhaps block at this time point. The result is, that the threads with the smallest work package are the fastest one.

 

notBlocking 

It's not so bad

I have to admit, my usage of std::async creates futures very contrived. At first, the futures were not bound to a variable. Second, I didn't use the future to pick up the result from the promise by a get or wait call. Exactly in that situation, we can observe the strange behavior, that the future blocks in its destructor.

The key reason for these posts was, to show, that a fire-and-forget future, which is not bound to a variable, must be handled with great care. But this point doesn't hold for futures, which are created by std::packaged_task or std::promise.

What's next?

I guess you know it. I'm not a big fan of condition variables. So I want to compare condition variables with tasks to synchronize threads. Because I believe, tasks are the most times the less error-prone and therefore the better choice. So, stay tuned for the next post. (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, 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, Daniel Hufschläger, Alessandro Pezzato, Evangelos Denaxas, Bob Perry, Satish Vangipuram, Andi Ireland, Richard Ohnemus, Michael Dunsky, Leo Goodstadt, Eduardo Velasquez, 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, Ralf Holly, Juan Dent, George Liao, and Daniel Ceperley.

 

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

 

 

My special thanks to Embarcadero CBUIDER STUDIO FINAL ICONS 1024 Small

 

My special thanks to PVS-Studio PVC Logo

 

Mentoring Program

My new mentoring program "Fundamentals for C++ Professionals" starts on the 22nd of April. Get more information here: https://bit.ly/MentoringProgramModernesCpp.

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: async, tasks

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 615

Yesterday 6623

Week 7238

Month 145630

All 9425653

Currently are 159 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments