#include #include #include // For runtime_error using namespace std ; mutex global_mutex; // A global mutex to protect shared resources void protected_function() { cout << "Attempting to acquire lock..." << endl; // lock_guard acquires the lock in its constructor // and automatically releases it in its destructor when it goes out of scope. lock_guard lock(global_mutex); cout << "Lock acquired." << endl; // Simulate some work that might throw an exception bool should_throw = true; // Set to true to demonstrate exception handling if (should_throw) { cout << "Throwing an exception..." << endl; throw runtime_error("Simulated error in critical section!"); } cout << "Work completed (this line won't be reached if exception is thrown)." << endl; // The lock_guard's destructor will be called here if no exception, // releasing the mutex. } // lock_guard goes out of scope here, releasing the mutex (even on exception) int main() { try { protected_function(); } catch (const runtime_error& e) { cerr << "Caught exception in main: " << e.what() << endl; } // Attempt to acquire the lock again to demonstrate it was released cout << "Attempting to acquire lock in main after protected_function..." << endl; lock_guard lock_in_main(global_mutex); cout << "Lock successfully acquired in main, demonstrating previous release." << endl; return 0; }