正文

多线程程序的分析浅见2008-11-05 17:41:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/lhlvc/39252.html

分享到:

     多线程程序的分析浅见 注:这只是我个人在学习过程中的理解,如有不正确之外还望大家批评指正。 情况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=””,说明处于有信号状态。再次进入线程再可以完成余下的工作。

阅读(1893) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册