1// lock_guard example
2#include <iostream> // std::cout
3#include <thread> // std::thread
4#include <mutex> // std::mutex, std::lock_guard
5#include <stdexcept> // std::logic_error
6
7std::mutex mtx;
8
9void print_even (int x) {
10 if (x%2==0) std::cout << x << " is even\n";
11 else throw (std::logic_error("not even"));
12}
13
14void print_thread_id (int id) {
15 try {
16 // using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:
17 std::lock_guard<std::mutex> lck (mtx);
18 print_even(id);
19 }
20 catch (std::logic_error&) {
21 std::cout << "[exception caught]\n";
22 }
23}
24
25int main ()
26{
27 std::thread threads[10];
28 // spawn 10 threads:
29 for (int i=0; i<10; ++i)
30 threads[i] = std::thread(print_thread_id,i+1);
31
32 for (auto& th : threads) th.join();
33
34 return 0;
35}