Choosing Thread Object

  • We now have three different ways to execute a task
    • Create an std::thread object
    • Create an std::packaged_task object
    • Call std::async()

Advantages of std::async()

  • The simplest way to execute a task

    • Easy to obtain the return value from a task
    • Or to catch any exception thrown in the task
    • Choice of running the task synchronously or asynchronously
  • Higher level abstraction than std::thread

    • The library manages the threads for the programmer
    • And the inter-thread communication
    • No need to use shared data

Disadvantages of async()

  • Cannot detach tasks
  • A task executed with std::launch::async is "implicitly joined"
{
  auto fut = std::async(std::launch::async, hello);
} // Calls ~fut()
  • The returned future's destructor will block
    • Until the task completes

Advantages of std::packaged_task

  • The best choice if we want to represent tasks as objects

    • e.g. to create a container of tasks
  • A lower level abstraction than std::async()

    • Can control when a task is executed
    • Can control on which thread it is executed

Advantages of std::thread

  • The most flexible
    • Allows access to the underlying software thread
    • Useful for features not supported by standard C++
    • Can be detached

Recommendations

  • For starting a new thread in general

    • Use std::async()
  • For containers of thread objects

    • Use std::packaged_task
  • For starting a detachable thread

  • For more specialized requirements

    • Use std::thread

C++ Asynchronous Programming Limitations

  • Lacks a number of important features

    • Continuations - "do this task, then do that task"
    • Only supports waiting on one future at a time
    • Waiting on multiple threads has to be done sequentially
    • Concurrent queue
  • These were planned for C++20, but were not included

    • Were to be implemented in C++23 using "executors"
    • Perhaps in C++26?

Third Party Libraries

  • Microsoft Parallel Patterns library
    • Windows only
  • Apple Grand Central Dispatch
    • Open Source, runs on Linux and Android
  • Intel oneAPI Thread Building Blocks
    • Open Source, runs on many platforms
  • HPX
    • Open Source, runs on many platforms