How do I wrap mutexes and locks with RAII?

In C++, using mutexes and locks is essential for ensuring thread safety in concurrent programming. To manage these locks efficiently and safely, you can leverage the RAII (Resource Acquisition Is Initialization) pattern. This means that the lifecycle of the lock is tied to the lifetime of an object, ensuring that the lock is always released when the object goes out of scope, even if an exception occurs.

Here’s a simple example demonstrating how to wrap a mutex with RAII in C++:

#include <iostream> #include <mutex> #include <thread> class LockGuard { public: LockGuard(std::mutex& mtx) : mtx(mtx) { mtx.lock(); } ~LockGuard() { mtx.unlock(); } private: std::mutex& mtx; }; void threadFunction(std::mutex& mtx) { LockGuard lock(mtx); // Lock is acquired here std::cout << "Thread is running..." << std::endl; // Mutex is automatically released when lock goes out of scope } int main() { std::mutex mtx; std::thread t1(threadFunction, std::ref(mtx)); std::thread t2(threadFunction, std::ref(mtx)); t1.join(); t2.join(); return 0; }

mutex lock RAII C++ thread safety concurrent programming resource management