Threading – Mutex vs. Atomic (C++)

Since C++11 you can use std::thread, std::mutex and std::atomic for your multithreaded projects. The biggest problem with multithreading is the race condition, which means you can’t tell which thread will at what time execute what code. The solution for this problem is to synchronise these dangerous code sections. The deault way to do this is to the usage of std::mutex at all these sections. This can be very annoying and you have to be careful to never create a possibility for a dead lock. A good way to may reduce the necessary usage of std::mutex are std::atomic. For all supported atomic types it is guaranteed that every read/write is happening encapsulated. These supported types have to be trivially copyable (memcpy), which includes primitive (like char, int, float, bool) and POD (Plain Old Data) types.


Sync with Mutex

std::mutex mtx;
int num = 0;

void inc() {
  std::lock_guard<std::mutex> lock(mtx);
  num++;
}

int main() {
  std::thread t1(inc), t2(inc);
  return 0;
}

Sync with Atomic

std::atomic<int> num = 0;

void inc() {
  num++;
}

int main() {
  std::thread t1(inc), t2(inc);
  return 0;
}