您的位置:首页 > 移动开发 > Objective-C

CreateMutex 和 WaitForSingleObject互斥对象

2016-10-25 22:23 417 查看
转自: http://blog.sina.com.cn/s/blog_6cbbf04b0100wijd.html

#include <windows.h>

#include <iostream>

using namespace std;

DWORD WINAPI Fun1Proc(

       LPVOID lpParameter

       );

DWORD WINAPI Fun2Proc(

       LPVOID lpParameter

       );

int index=0;

int tickets=100;

HANDLE hMutex;

void main()

{

 HANDLE hThread1;

 HANDLE hThread2;

 hMutex=CreateMutex(NULL,TRUE,NULL); //FALSE意思为没有被占用,有信号状态  +1

 WaitForSingleObject(hMutex,INFINITE);// +1

 ReleaseMutex(hMutex);                // -1

 ReleaseMutex(hMutex);                // -1

 hThread1=CreateThread(NULL,0,Fun1Proc,NULL,0,NULL);

 hThread2=CreateThread(NULL,0,Fun2Proc,NULL,0,NULL);

 CloseHandle(hThread1);

 CloseHandle(hThread2);

 Sleep(4000);

}

DWORD WINAPI Fun1Proc(

       LPVOID lpParameter

       )

{

 while(TRUE)

 {      

    

      WaitForSingleObject(hMutex,INFINITE);

            if(tickets>0)

   {  

    Sleep(1);//放弃执行权利 另一个线程运行

    cout<<"thread1 sell the 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 the ticket: "<<tickets--<<endl;

  }

  else

   break; 

  ReleaseMutex(hMutex);

 }

 return 0;

}

//////////////////

关于WaitForSingleObject(hMutex,INFINITE);内部会有一个计数器,根据申请或者释放自行加减1

hMutex=CreateMutex(NULL,TRUE,NULL);   若设置为TRUE,申请同时就被主线程占用。

hMutex=CreateMutex(NULL,FALSE,NULL);  若设置为FALSE,则申请后不被占用。

 

 

上文例子中的计数器加减情况如下。

                 hMutex=CreateMutex(NULL,TRUE,NULL);//FALSE意思为没有被占用,有信号状态  +1

                 WaitForSingleObject(hMutex,INFINITE);      // +1

                 ReleaseMutex(hMutex);                                 // -1

                 ReleaseMutex(hMutex);                                 // -1

由于上述例子中,waitforsingleobject是放在主线程上,所以线程Fun1Proc和Fun2Proc必须要在主线程的计数器为0的时候才能申请到“位置”,若不为零,不可以轮到1,2执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息