Monday, September 18, 2017

C++11: Promise

C++11 added template class std::promise that enables a thread to store a value or exception that can be accessed by another thread. Here is an example:

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

class FunctionClass
{
 private:
  std::string mThreadName;
  int         mSleepTime;
  
 public:
  void operator()(std::promise promise)
  {
    std::this_thread::sleep_for(
                        std::chrono::milliseconds(mSleepTime));
    for (int i = 0; i < 3; i++)
    {
      std::cout << mThreadName;
    }
    std::cout << " ";
    promise.set_value(mSleepTime + 1000);
  }
  FunctionClass(std::string threadName, int sleepTime)
  : mThreadName(threadName), mSleepTime(sleepTime)
  {}
};

int main()
{
  FunctionClass f1("F1", 100);

  std::promise<int> promise1;
  std::future<int>  future1 = promise1.get_future();
  std::thread       t1(f1, std::move(promise1));

  future1.wait();
  std::cout << future1.get() << std::endl;

  t1.join();

  return 0;
}
// Output: F1F1F1 1100
Reference: http://en.cppreference.com/w/cpp/thread/promise

No comments:

Post a Comment