Future & Promises

Transferring Data Between Threads

  • std::thread does not provide a way to return a value

    • So far, we have used a shared variable
    • Access to the shared variable needs to be protected by locks
  • Condition variables allow us to coordinate threads

    • A thread can signal to another thread that shared data has been modified
    • Cannot directly transfer data from one thread to another

std::future and std::promise

  • Classes for transferring data between threads
  • Together, these set up a "shared state" between threads
  • The shared state can transfer data from one thread to another
    • No shared data variables
    • No explicit locking

Producer-Consumer Model

  • Futures and promises use a Producer-Consumer model
    • Reader / writer threads are an example of this model
  • A "producer" thread will generate a result
  • A "consumer" thread waits for the result
  • The producer thread generates the result
  • The producer thread stores the result in the shared state
  • The consumer thread reads the result from the shared state

Transfer of Data using Future and Promise

  • An std::promise is associated with the producer
  • An std::future object is associated with the consumer
    • The consumer calls a member function or the future object
    • The function blocks until the result becomes available
  • The producer threads sends the result
    • The promise object stores the result in the shared state
  • The consumer thread receives the result

Exception Handling

  • Futures and promises also work with exceptions
    • The promise stores the exception in the shared state
  • This exception will be rethrown in the consumer thread
    • By the future's blocking function
  • The producer thread "throws" the exception to the consumer