Monday, September 18, 2017

C++11: Future

C++11 added template class std::future that enables a thread to access the result of an asynchronous operation. Here is an example:

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

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

int main()
{
  FunctionClass f1("F1", 300);
  FunctionClass f2("F2", 200);
  FunctionClass f3("F3", 100);

  std::packaged_task<int()> task3(f3)           ;
  std::future<int>          future3             = task3.get_future();
  std::thread               t1(f1)              ;
  std::thread               t2(f2)              ;
  std::thread               t3(std::move(task3));

  future3.wait();
  std::cout << future3.get();

  t1.join();
  t2.join();
  t3.join();

  std::cout << std::endl;
  return 0;
}
// Output: F3F3F31100F2F2F2F1F1F1
Reference: http://en.cppreference.com/w/cpp/thread/future

No comments:

Post a Comment