LPCTSTR lpName ); //名称
使用互斥线程,按照谁先等候谁先拥有互斥量的规则顺序执行.(以后都按这个顺序执行)
OpenMutex 打开已存在的有名互斥量,返回互斥量句柄
你想在一个进程中创建了一个有名字的互斥量,想在别的进程中使用这个互斥量的时候,就用此函数指定互斥量名字来得到互斥量的句柄
// Mutex.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "conio.h" #include "windows.h" HANDLE g_hMutex = NULL; DWORD WINAPI ThreadProc1( LPVOID pParam ) { while( 1 ) { //等候互斥量 WaitForSingleObject( g_hMutex, INFINITE ); printf( "ThreadProc1----------\n"); Sleep( 500 ); //释放互斥量 ReleaseMutex( g_hMutex ); } return 0; } DWORD WINAPI ThreadProc2( LPVOID pParam ) { while( 1 ) { //等候互斥量 WaitForSingleObject( g_hMutex, INFINITE ); printf( "------ThreadProc2------\n"); Sleep( 500 ); //释放互斥量 ReleaseMutex( g_hMutex ); } return 0; } DWORD WINAPI ThreadProc3( LPVOID pParam ) { while( 1 ) { //等候互斥量 WaitForSingleObject( g_hMutex, INFINITE ); printf( "------------ThreadProc3\n"); Sleep( 500 ); //释放互斥量 ReleaseMutex( g_hMutex ); } return 0; } void Create( ) { DWORD nThreadID = 0; HANDLE hThread[3] = { NULL }; hThread[0] = CreateThread( NULL, 0, ThreadProc1, NULL, 0, &nThreadID ); hThread[1] = CreateThread( NULL, 0, ThreadProc2, NULL, 0, &nThreadID ); hThread[2] = CreateThread( NULL, 0, ThreadProc3, NULL, 0, &nThreadID ); } int main(int argc, char* argv[]) { //创建互斥量 g_hMutex = CreateMutex( NULL, FALSE, NULL ); Create( ); getch( ); //关闭 CloseHandle( g_hMutex ); return 0; }