#include #include #include using namespace std ; mutex myMutex ; void protectedFunction() { lock_guard lock(myMutex) ; // Locks myMutex cout << "Inside protected function." << endl; lock_guard lock1 = lock ; // ... critical section code ... } // myMutex is automatically unlocked when 'lock' goes out of scope void anotherFunction( lock_guard lockGuardObject ) { } int main() { lock_guard lock1(myMutex); // Locks myMutex cout << "Lock1 acquired." << endl; anotherFunction( lock1 ) ; // The following line would result in a compilation error: // lock_guard lock2 = lock1; // ERROR: Cannot copy lock_guard // You also cannot pass a lock_guard by value to a function: // void anotherFunction(lock_guard l) {} // anotherFunction(lock1); // ERROR: Cannot copy lock_guard thread t1(protectedFunction); t1.join(); cout << "Lock1 released." << endl; // lock1 goes out of scope here return 0; }