Async and Launch Options

  • std::async() may start a new thread for the task
  • Or it may run the task in the same thread
  • Controlled by the "launch flag"
    • Optional argument to std::async()

Launch Flags

  • std::launch::async

    • A new thread is started for the task
    • The task is executed as soon as the thread starts
  • std::launch::deferred

    • Nothing happens until get() is called on the returned future
    • The task is then executed ("lazy evaluation")
  • If both flags are set

    • The implementation decides whether to start a new thread
    • This is the default

Default Launch Policy

  • Lack of certainty

    • The task could execute synchronously with the initiating thread
    • The task could execute concurrently with the initiating thread
    • It could execute concurrently with the thread that calls get()
    • If get() is not called, the task may not execute at all
  • Thread local storage (TLS)

    • We do not know which thread's data will be used

Launch Policy Recommendations

  • Use the async launch option if any of these are true

    • The task must execute in a separate thread
    • The task must start immediately
    • The task will use thread-local storage
    • The task function must be executed, even if get() is not called
    • The thread receiving the future will call wait_for() or wait_until()
  • Use the deferred launch option if

    • The task must be run in the thread which calls get()
    • The task must be executed, even if no more threads can be created
    • You want lazy execution of the task
  • Otherwise, let the implementation choose

Return Value from wait() and Friends

  • wait() Returns nothing

  • wait_for()

  • wait_until()

    • Return std::future_status::ready if the result is available
    • Return std;;future_status::timeout if the timeout has expired
    • Return std::future_status::deferred if the result is being lazily evaluated
  • In lazy evaluation, the task does not run until get() is called