线程安全-互斥体
内核版的令牌
相关函数
HANDLE CreateMutexA( LPSECURITY_ATTRIBUTES lpMutexAttributes, BOOL bInitialOwner,//FALSE的时候,互斥体创建出来就可以用 LPCSTR lpName );
示例代码,下面是两个程序,代表两个进程,两个进程中抢同一个内核令牌
//A进程代码 int main() { //创建令牌 HANDLE g_mutex = CreateMutex(NULL,FALSE,"HEHE"); //获取令牌 WaitForSingleObject(g_mutex,INFINITE); for(int i=0;i<10;i++) { Sleep(5000); printf("这是A进程。。。。%d\n",i); } //释放令牌 ReleaseMutex(g_mutex); return 0; } //B进程代码 int main() { //创建令牌 HANDLE g_mutex = CreateMutex(NULL,FALSE,"HEHE"); //获取令牌 WaitForSingleObject(g_mutex,INFINITE); for(int i=0;i<10;i++) { Sleep(5000); printf("这是B进程。。。。%d\n",i); } //释放令牌 ReleaseMutex(g_mutex); return 0; }
对于CreateMutex函数的官方说明
If the function succeeds, the return value is a handle to the newly created mutex object. If the function fails, the return value is NULL. To get extended error information, call GetLastError. If the mutex is a named mutex and the object existed before this function call,
the return value is a handle to the existing object, OpenMutexa> function.
可以实现一个程序只运行一份(单开)