Monday, September 11, 2017

C++11: Locks

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

#include <iostream>
#include <mutex>
#include <thread>

int gSharedData[2] = {1, 1};
std::mutex gMutex;

void updateData()
{
  std::unique_lock<std::mutex> lock(gMutex);
  gSharedData[0] = gSharedData[0] + 1;
  gSharedData[1] = gSharedData[1] + 1;
  std::cout << gSharedData[0] << " " << gSharedData[1] << " ";
}

struct FunctionClass
{
  void operator()()
  {
    int temp = 0;
    for (int i = 0; i < 3; i++)
    {
      updateData();
    }
  }
};

int main()
{
  std::thread t1{FunctionClass()};
  std::thread t2{FunctionClass()};
  std::thread t3{FunctionClass()};

  t1.join();
  t2.join();
  t3.join();
  std::cout << std::endl;
  return 0;
}
// Output: 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9 10 10
Reference: https://isocpp.org/wiki/faq/cpp11-library-concurrency#std-lock

No comments:

Post a Comment