线程同步-互斥

临界区本身不是内核对象,它是工作在用户态的,所以速度快一些
互斥量、信号量、事件都是Windows的内核对象,当程序对这些对象进行控制时会自动转换到核心态。

C++ 方式

/// 实例容器锁
mutable std::mutex mutMapInst;

{
std::lock_guard<std::mutex>lk(m_devInfo.mutMapInst);
m_devInfo.mapInst.emplace(make_pair(instId, &dev));
}

MFC 方式

CMutex Mutex;

CSingleLock SingleLock(&Mutex);
SingleLock.Lock();

Win32 方式

CRITICAL_SECTION cs;

InitializeCriticalSection(&m_curInfo.cs);

EnterCriticalSection(&m_curInfo.cs);
m_curInfo.timeCmp = time(NULL);
LeaveCriticalSection(&m_curInfo.cs);

DeleteCriticalSection(&m_curInfo.cs);

同步事件

// 同步发送数据的,读取完毕后,在发送
HANDLE m_hEvent_write;

m_hEvent_write = CreateEvent(
NULL, // default security attributes
TRUE, // manual-reset event
FALSE, // initial state is nonsignaled
TEXT("WriteEvent") // object name
);

WaitForSingleObject(pwnd->m_hEvent_write, INFINITE);
// go on
::SetEvent(m_hEvent_write);