c++ 进程锁 WaitForSingleObject emutex

1.函数

CreateMutex()//创建一个互斥体
OpenMutex()//打开一个互斥体
WaitForSingleObject()//尝试加锁
ReleaseMutex()//解锁

2.代码

a) 文件 emutex.h

#include 
//进程锁,不支持 linux

class emutex
{
public:
	bool createMutex(char *name);//创建互斥锁
	bool openMutex(char *name);//打开互斥锁

	void lock();//上锁
	void unlock();//解锁

private:
	HANDLE m_mutex;//句柄缓存
};

b)文件 emutex.cpp

#include "emutex.h"
#include "../str/str.h"

//创建互斥锁
bool emutex::createMutex(char *name)
{
	m_mutex = CreateMutex(NULL, false, str::btow_e(name));
	return m_mutex > 0 ? true : false;
}

//打开互斥锁
bool emutex::openMutex(char *name)
{
	m_mutex = OpenMutex(SYNCHRONIZE, false, str::btow_e(name));
	return m_mutex > 0 ? true : false;
}

//上锁
void emutex::lock()
{
	while (WaitForSingleObject(m_mutex, 0) == WAIT_TIMEOUT) //INFINITE 阻塞方式,效率低
	{
		Sleep(1);
	};
}

//解锁
void emutex::unlock()
{
	ReleaseMutex(m_mutex);
}

函数 str::btow_e

//char* 转 wchar_t*
wchar_t* str::btow_e(const char *buf)
{
	int _dBufsize = MultiByteToWideChar(CP_ACP, 0, buf, strlen(buf) + 1, NULL, 0);
	wchar_t *_wbuf = new wchar_t[_dBufsize];
	wmemset(_wbuf, 0, _dBufsize);
	int _error = MultiByteToWideChar(CP_ACP, 0, buf, strlen(buf) + 1, _wbuf, _dBufsize);
	if (_error <= 0)
	{
		delete _wbuf;
		_wbuf = NULL;
	}

	return _wbuf;
}

 

你可能感兴趣的:(c++)