Back to TILs

C++ lock_guard

Date: 2023-01-09Last modified: 2024-02-26

Table of contents

std::mutex mtx;

void print_even(int x) {
  if (x % 2 == 0)
    std::cout << x << " is even\n";
  else
    throw(std::logic_error("not even"));
}

void print_thread_id(int id) {
  try {
    // using a local lock_guard to lock mtx guarantees unlocking on destruction
    // / exception:
    std::lock_guard<std::mutex> lck(mtx);
    print_even(id);
  } catch (std::logic_error&) {
    std::cout << "[exception caught]\n";
  }
}

int main() {
  std::thread threads[10];
  // spawn 10 threads:
  for (int i = 0; i < 10; ++i) {
    threads[i] = std::thread(print_thread_id, i + 1);
  }

  for (auto& th : threads) {
    th.join();
  }

  return 0;
}

Possible output

[exception caught]
6 is even
[exception caught]
[exception caught]
[exception caught]
8 is even
10 is even
4 is even
2 is even
[exception caught]

References