mercredi 16 mai 2018

The best way to lock_guard MFC CMutex (like std::guard)?

I upgrade an old MFC multi-threaded C++ project (from year 2002) to VS2017 Windows 10 x64. I re-write the mutex sections (MFC's CMutex m_mu). I preferred, of course, to use c++11 std::mutex m_mutex and std::guard<std::mutex> m_mutex but it throws an exception, probably because m_mutex is a member of a static object. As a result: I decided to add my own CGuard class (code below).

Any code-criticism? ..Any code-improvements? ..Any better ideas?

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

void CMonitorsManager::OnMonitorLoginMessageArrive
                        (CMonitorLoginMessage* pMessage)
{
    CGuard Guard(&m_mutex);

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

Guard.h file:

#pragma once

#include <afxmt.h>//for CMutex

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

    void Unlock();

protected:
    CMutex* m_pMutex = nullptr;
};

Guard.cpp file:

#include "stdafx.h"
#include "Guard.h"

CGuard::CGuard(CMutex* pMutex)
{
    pMutex->Lock();

    m_pMutex = pMutex;
}

void CGuard::Unlock()
{
    m_pMutex->Unlock();
    m_pMutex = nullptr;
}

CGuard::~CGuard()
{
    if (m_pMutex)
        m_pMutex->Unlock();
}

Aucun commentaire:

Enregistrer un commentaire