[in] Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If
lpMutexAttributes is NULL, the handle cannot be inherited.
does not obtain ownership of the mutex. To determine if the caller created the mutex, see the Return Values section.
lpName[in] Pointer to a null-terminated string specifying the name of the mutex object. The name is limited to MAX_PATH characters. Name comparison is case sensitive.
If lpName matches the name of an existing named mutex object, this function requests MUTEX_ALL_ACCESS access to the existing object. In this case, thebInitialOwner parameter is ignored because
it has already been set by the creating process. If the lpMutexAttributes parameter is not NULL, it determines whether the handle can be inherited, but its security-descriptor member is ignored.
If lpName is NULL, the mutex object is created without a name.
If lpName matches the name of an existing event, semaphore, waitable timer, job, or file-mapping object, the function fails and the GetLastError function returns ERROR_INVALID_HANDLE. This
occurs because these objects share the same name space.
Terminal Services: The name can have a "Global\" or "Local\" prefix to explicitly create the object in the global or session name space. The remainder of the name can contain any character except the backslash
character (\). For more information, see Kernel Object Name Spaces.
参数lpName指定是一个命名的互斥对象还是一个匿名的互斥对象,它们之间的区别我们留待后面再学习
该函数释放互斥对象的所有权,也就是说该函数将互斥对象置为有信号的状态该函数的参数即为CreateMutex函数返回的句柄对象
在利用互斥事件进行线程同步的时候我们还需要使用一个函数WaitForSingleObject该函数将等待互斥对象有状态才返回否则一直阻塞。
#include <windows.h>
#include <stdio.h> static int number=;
HANDLE Mutex; DWORD WINAPI ThreadOne(LPVOID lpParameter)
{
while()
{
WaitForSingleObject(Mutex,INFINITE);
if(number>)
{
printf("窗口1售出第%d张票...\n",number);
number--;
Sleep();
}
ReleaseMutex(Mutex);
}
return ;
}
DWORD WINAPI ThreadTwo(LPVOID lpParameter)
{
while()
{
WaitForSingleObject(Mutex,INFINITE);
if(number>)
{
printf("窗口2售出第%d张票...\n",number);
Sleep();
number--;
}
ReleaseMutex(Mutex);
}
return ;
} int main()
{
HANDLE HOne,HTwo;
Mutex=CreateMutex(NULL,FALSE,NULL);
printf("***********************vpoet******************\n");
HOne=CreateThread(NULL,,ThreadOne,NULL,,NULL);
printf("窗口1售票开始:\n");
HTwo=CreateThread(NULL,,ThreadTwo,NULL,,NULL);
printf("窗口2售票开始:\n");
CloseHandle(HOne);
CloseHandle(HTwo);
while(TRUE)
{
if(number==)
{
printf("不好意思,票卖完了!\n");
CloseHandle(Mutex);
return ;
}
else
{
continue;
}
} return ;
}