二 API
Mutex function Description CreateMutexCreates or opens a named or unnamed mutex object. CreateMutexExCreates or opens a named or unnamed mutex object and returns ahandle to the object. OpenMutexOpens an existing named mutex object. ReleaseMutexReleases ownership of the specified mutex object.
三 实例
来自msdn的实例:程函数中有一个循环,在每个循环的开始都取得Mutex,然后对全局或静态操作,相当于在关键代码段操作,然后在使用完以后释放它,大家可以执行,查看结果。
#include<windows.h>
#include<stdio.h>
#defineTHREADCOUNT 64 //less than 64
HANDLEghMutex;
int g_x =0;
DWORD WINAPIWriteToDatabase(LPVOID);
voidmain()
{
HANDLEaThread[THREADCOUNT];
DWORDThreadID;
inti;

//Create a mutex with no initial owner
ghMutex = CreateMutex(
NULL,// default security attributes
FALSE,// initially not owned
NULL);// unnamed mutex
if(ghMutex == NULL)
{
printf('CreateMutex error: %d\n', GetLastError());
return;
}
//Create worker threads
for(i=0; i < THREADCOUNT; i++ )
{
aThread[i] = CreateThread(
NULL,// default security attributes
0, //default stack size
(LPTHREAD_START_ROUTINE) WriteToDatabase,
NULL,// no thread function arguments
0, //default creation flags
&ThreadID); // receive thread identifier
if(aThread[i] == NULL )
{
printf('CreateThread error: %d\n', GetLastError());
return;
}
}
//Wait for all threads to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
//Close thread and mutex handles
for(i=0; i < THREADCOUNT; i++ )
CloseHandle(aThread[i]);
CloseHandle(ghMutex);

printf('g_x is :%d\n',g_x);
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-25584-2.html
对自己定位清晰的boy
实力就是裁判