多线程程序的分析浅见 注:这只是我个人在学习过程中的理解,如有不正确之外还望大家批评指正。 情况1: #include<windows.h> #include<iostream.h> DWORD WINAPI Fun1Proc(LPVOID lpParameter); DWORD WINAPI Fun2Proc(LPVOID lpParameter); int tickets=100; HANDLE hMutex; void main() { HANDLE hThread1; HANDLE hThread2; hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL); CloseHandle(hThread1); CloseHandle(hThread2); hMutex=CreateMutex(NULL,FALSE,NULL); Sleep(4000); } DWORD WINAPI Fun1Proc(LPVOID lpParameter) { while(TRUE) { WaitForSingleObject(hMutex,INFINITE); if(tickets>0) { Sleep(1); cout<<"thread1 sell ticket:"<<tickets--<<endl; } else break; ReleaseMutex(hMutex); } return 0; } DWORD WINAPI Fun2Proc(LPVOID lpParameter) { while(TRUE) { WaitForSingleObject(hMutex,INFINITE); if(tickets>0) { Sleep(1); cout<<"thread2 sell ticket:"<<tickets--<<endl; } else break; ReleaseMutex(hMutex); } return 0; } 分析:在main函数中用CreateMutex创建了一个互斥对象。因为互斥对象是一个内核对象,此时系统将维护一个引用计数(count=1),由于参数为FLASE,线程ID没有被主线程标识。当控制权进入Fun1Proc线程时则用WaitForSingleObject 请求互斥对象时发现在count=1,说明互斥对象处于有信号状态(count=2,ID=Fun1Proc)。当Fun1Proc线程时间片到时,进入Fun2Proc线程的WaitForSingleObject,发现hMutex被线程1占用,线程2时间片到后则进入线程1的if…else模块执行,完成后进入ReleaseMutex(hMutex)释放Fun1Proc线程的互斥对象。此时hMutex的count=1,id=””,说明处于有信号状态。再次进入线程再可以完成余下的工作。

评论