Monday, September 11, 2017

C++11: Threads

C++11 added threading. Here is an example:

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

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

int main()
{
  FunctionClass f1("F1", 3);
  FunctionClass f2("F2", 2);
  FunctionClass f3("F3", 1);

  std::thread t1(f1);
  std::thread t2(f2);
  std::thread t3(f3);

  t1.join();
  t2.join();
  t3.join();
  std::cout << std::endl;
  return 0;
}
// Output: F3F3F3F2F2F2F1F1F1
Reference: https://isocpp.org/wiki/faq/cpp11-library-concurrency#std-threads

No comments:

Post a Comment