互斥量

来源:互联网 发布:寻梦环游记 知乎 编辑:程序博客网 时间:2024/05/21 06:56
HANDLE CreateMutex(  LPSECURITY_ATTRIBUTES lpMutexAttributes,  BOOL bInitialOwner,  LPCTSTR lpName);
1:lpMutexAttributes应该设为NULL
2:bInitialOwner指定调用线程是否立刻拥有刚刚创建线程的互斥量的所有权
3:lpName在调用CreateMutex时检查是否有相同名称的互斥量已经创建,如果已经创建,则返回已经创建的互斥量的句柄。为确定互斥量是否存在
   需要调用GetLastError,如果它返回ERROR_ALREADY_EXISTS,则表示该互斥量已存在,那么即使上面的bInitialOwner设置为TRUE也不能
   无法立刻拥有该互斥量
调用WaitForSingleObject将获取互斥量,ReleaseMutex将释放互斥量,注意调用WaitForSingleObject和ReleaseMutex的次数必须相等
线程MyThread1和Mythread2将交替打印i的值

// MyThread.cpp : Defines the entry point for the console application.

//

 

#include "stdafx.h"

#include <windows.h>

#include <commctrl.h>

 

HANDLE hMutex;

 

DWORD MyThread1(VOID)

{

     INT32 i = 0;

 

     while(1) {

         WaitForSingleObject(hMutex, INFINITE);

         printf("1:%d/n",i++);

         ReleaseMutex(hMutex);

     }

 

     return 0;

}

 

DWORD MyThread2(VOID)

{

     INT32 i = 0;

 

     while(1) {

         WaitForSingleObject(hMutex, INFINITE);

         printf("2:%d/n",i++);

         ReleaseMutex(hMutex);

     }

 

     return 0;

}

 

int _tmain(int argc, _TCHAR* argv[])

{

     HANDLE hThread1;

     HANDLE hThread2;

 

     hMutex = CreateMutex(NULL,FALSE,NULL);

     if(NULL == hMutex) {

         printf("Create hMutex error/n");

         return -1;

     }

 

     hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread1, NULL, 0, NULL);

     if(hThread1)  {

         printf("CreateThread MyThread1 success/r/n");

     }    else {

         printf("CreateThread MyThread1 error/r/n");

         return -1;

     }   

 

     hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)MyThread2, NULL, 0, NULL);

     if(hThread2)  {

         printf("CreateThread MyThread2 success/r/n");

     }    else {

         printf("CreateThread MyThread2 error/r/n");

         return -1;

     }

    

     while(1) {

         Sleep(1000);

     }

    

 

     CloseHandle(hThread1);

     CloseHandle(hThread2);

 

     return 0;

}