Monday, September 18, 2017

C++11: Async

C++11 added the template function async that runs a function asynchronously. 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;
    }
    std::cout << " ";
    return mSleepTime + 1000;
  }
  FunctionClass(std::string threadName, int sleepTime)
  : mThreadName(threadName), mSleepTime(sleepTime)
  {}
};

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

  auto handle = std::async(std::launch::async, f1);

  std::cout << handle.get() << std::endl;

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

No comments:

Post a Comment