// Mutex.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "windows.h" #include "conio.h" HANDLE g_nMutex=NULL; int g_ncount=0; DWORD WINAPI ThreadProcl1(LPVOID pParam){ while(1){ //等候互斥 WaitForSingleObject(g_nMutex,INFINITE); printf("ThreadProcl1------------\n"); g_ncount++; printf("%d\n",g_ncount); Sleep(500); //释放互斥量 ReleaseMutex(g_nMutex); } return 0; } DWORD WINAPI ThreadProcl2(LPVOID pParam){ while(1){ WaitForSingleObject(g_nMutex,INFINITE); printf("------------ThreadProcl2\n"); g_ncount++; printf("%d\n",g_ncount); Sleep(500); ReleaseMutex(g_nMutex); } return 0; } DWORD WINAPI ThreadProcl3(LPVOID pParam){ while(1){ WaitForSingleObject(g_nMutex,INFINITE); printf("-------ThreadProcl3-----\n"); g_ncount++; printf("%d\n",g_ncount); Sleep(500); //重置互斥 ReleaseMutex(g_nMutex); } return 0; } void Create(){ DWORD tID=0; HANDLE hThread[3]={NULL}; hThread[0]=CreateThread(NULL,0,ThreadProcl1,NULL,0,&tID); hThread[1]=CreateThread(NULL,0,ThreadProcl2,NULL,0,&tID); hThread[2]=CreateThread(NULL,0,ThreadProcl3,NULL,0,&tID); } int main(int argc, char* argv[]) { //创建互斥 第二个参数如果是true 就表示当前开始线程也加入了互斥 //这样的话 MAIN也是一个线程 必须把MAIN函数执行完才执行线程1线程2 //可是mian线程结束了 我们程序也结束了 线程1这些也不会执行 所以没什么意思 g_nMutex=CreateMutex(NULL,false,NULL); Create(); getch(); CloseHandle(g_nMutex); return 0; }