文档导航目录(5 专栏 / 65 篇)

9-互斥体

win32基础 更新于 2024-03-16 1 分钟 0 次阅读 0 条评论

内核级的临界资源访问怎么办?

article image

互斥体可以解决跨进程的临界资源访问问题。

互斥体是一种可以放在内核中的令牌。

article image

创建互斥体函数

c++
HANDLE CreateMutex(
    LPSECURITY_ATTRIBUTES lpMutexAttributes,
     // pointer to security attributes
    BOOL bInitialOwner,
     // flag for initial ownership
    LPCTSTR lpName
     // pointer to mutex-object name
);

代码示例:

c++
int main()
{
	//创建一个互斥体, FALSE表示创建互斥体后立马有信号,可以使用
	HANDLE hMutex = CreateMutex(NULL, FALSE, TEXT("mutex"));

	//获取令牌:有信号,线程的拥有者
	WaitForSingleObject(hMutex, INFINITE);

	for (int i=0;i<10;i++)
	{
		Sleep(500);
		printf("+++++++%d\n", i);
	}

	//释放令牌
	ReleaseMutex(hMutex);

	return 0;
}

互斥体与线程锁的区别:

  1. 线程锁只能用于单个进程间的线程控制
  2. 互斥体可以设定等待超时,但线程锁不能
  3. 线程意外终结时,Mutex可以避免无限等待
  4. Mutex效率没有线程锁高

可以使用互斥体来防止多开

创建互斥体的返回值:

plain text
If the function succeeds, the return value is a handle to the mutex object. If the named mutex object existed before the function call, the GetLastError function returns ERROR_ALREADY_EXISTS. Otherwise, GetLastError returns zero.
If the function fails, the return value is NULL. To get extended error information, call GetLastError.

当已经存在一个互斥体后,在创建互斥体时,使用GetLastError函数会返回ERROR_ALREADY_EXISTS错误。以此来判断程序是否多开。

c++
	DWORD dwRet = GetLastError();
	if (hMutex)
	{
		if (ERROR_ALREADY_EXISTS == dwRet)
		{
			CloseHandle(hMutex);
			return 0;
		}
	} 
	else
	{
		printf("创建失败,程序退出!");
		CloseHandle(hMutex);
		return 0;
	}

评论讨论 (0) Artalk 自托管