LockGuard for MFC CMutex I upgrade an old MFC multi-threaded C++ project (from year 2002) to VS2017 Windows 10 x64. I rewrote the mutex sections (MFC's CMutex m_mu). I preferred, of course, to use C++11 std::mutex m_mutex and std::lock_guard&lt;std::mutex&gt; guard(m_mutex) but it throws an exception. I decided to add my own CLockGuard class (code below).

Example: (m_mutex is a protected MFC CMutex member of CMonitorsManager)

void CMonitorsManager::OnMonitorLoginMessageArrive
                        (CMonitorLoginMessage* pMessage)
{
    CLockGuard LockGuard(&amp;m_mutex);

    m_MonitorId2IPMap.SetAt(pMessage-&gt;GetDeviceAddress(),
                            pMessage-&gt;GetPeerAddress());
};


LockGuard.h file:

#pragma once

#include &lt;afxmt.h&gt;//for CMutex

class CLockGuard
{
public:
    CLockGuard(CMutex* rMutex);
    ~CLockGuard();

    void Unlock();

protected:
    CMutex* m_pMutex = nullptr;
};


LockGuard.cpp file:

#include "stdafx.h"
#include "LockGuard.h"

CLockGuard::CLockGuard(CMutex* pMutex)
{
    pMutex-&gt;Lock();

    m_pMutex = pMutex;
}

void CLockGuard::Unlock()
{
    m_pMutex-&gt;Unlock();
    m_pMutex = nullptr;
}

CLockGuard::~CLockGuard()
{
    if (m_pMutex)
        m_pMutex-&gt;Unlock();
}
Instead of writing your own lock_guard-like object specifically to use with a CMutex, I'd write a wrapper for CMutex to give it the Lockable interface, then just use it with a normal std::lock_guard:

namespace mfc {
class mutex {
    CMutex m;
public:
    mutex(BOOL bInitiallyOwn = FALSE,  
          LPCTSTR lpszName = NULL,  
          LPSECURITY_ATTRIBUTES lpsaAttribute = NULL) 
        : m(bInitiallyOwn, lpszName, lpsaAttribute) 
    {}

    void lock() { m.Lock(); }
    void unlock() { m.Unlock(); }
};


Then you can just lock it like you would an std:mutex:

// Define the mutex
mfc::mutex m;

void foo() { 
    std::lock_guard&lt;mfc::mutex&gt; L(m);
    // use whatever m is protecting
}


You may not even need that though. You may have run into the fact that a Windows-native mutex is always a recursive mutex, and a std::mutex is not. If you replace it with std::recursive_mutex instead of std::mutex, it may work just fine (or depending on how you do your locking, you may need a recursive_timed_mutex).