Sample
// Why Simple, Why Beautifu
#include <mutex>
#include <thread>
int g_var = 1;
std::mutex mtx;
static void thread_1_handler(void)
{
{
std::lock_guard<std::mutex> guard(mtx);
g_var = 3;
}
}
int main(void)
{
{
std::lock_guard<std::mutex> guard(mtx);
g_var = 2;
}
std::thread thread_1(thread_1_handler);
return 0;
}
How works
//use reference, and de-contructure when out of variable range
template<typename _Mutex>
class lock_guard
{
public:
typedef _Mutex mutex_type;
explicit lock_guard(mutex_type& __m) : _M_device(__m)
{ _M_device.lock(); }
lock_guard(mutex_type& __m, adopt_lock_t) noexcept : _M_device(__m)
{ } // calling thread owns mutex
~lock_guard()
{ _M_device.unlock(); }
lock_guard(const lock_guard&) = delete;
lock_guard& operator=(const lock_guard&) = delete;
private:
mutex_type& _M_device;
};