#include #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 cout << "Work completed (this line won't be reached if exception is thrown)." << endl; } // lock_guard goes out of scope here, releasing the mutex (even on exception) int main() { lock_guard lock(global_mutex) ; thread t1( protected_function ); thread t2( protected_function ); t1.join() ; t2.join() ; return 0; }