Skip to content

Running multiple threads

Basic control – low level interface

  • std::thread
    you can explicitly write and start your own thread function
  • std::promise and std::future
    as a standard mechanism of exchanging both return values and exceptions between your thread function and some environment code you can write the results to a promise. The interested code can access these results with use of a future which is connected to the promise.

Advanced teatures – high level interface

  • std::async
    you can leave the details about asynchronous code execution to the C++ runtime. Depending on your processor’s characteristics and the complexity of your code the code may be executed synchronously or really asynchronous within a separate thread. As you are always accessing results through a future this will work for both the synchronous and the asynchronous case.
  • std::packaged_task
    you can store execution code within packaged_tasks for later execution (e.g. by passing them to some threads from your thread pool as soon as they become available). Again results are accessed via futures which are attached to the packaged_tasks.