您的位置:首页 > 其它

线中的互斥量

2016-01-15 09:06 239 查看
多个线程使用同一个变量,可以用互斥体进行保护。
#include <windows.h>
#include <stdio.h>
#pragma hdrstop
#pragma argsused

#define NUM_THREADS 4
DWORD dwCounter = 0;
HANDLE hMutex;       //声明互斥变量
void UseMutex(void);
DWORD WINAPI MutexThread(LPVOID lpParam);
int a[4]={1,2,3,4};
//---------------------------------------------------------------------------

int main(int argc, char* argv[])
{
UseMutex();
getchar();
return 0;
}
//---------------------------------------------------------------------------
void  UseMutex()
{
   int i;
   HANDLE hThread;
   //创建互斥变量,第二个参数为初始状态,如果为true,则互斥量为当前进程拥有
   //需要ReleaseMutes线程回调函数才能运行
   hMutex = CreateMutexA(NULL,false,NULL);
   if(hMutex == NULL)
   {
      printf("互斥量创建不成功: %d\n",GetLastError());
   }
   else
   {
      printf("创建互斥量成功!\n");
   }
   for(i = 0;i< NUM_THREADS ;i++)
   {
      printf("创建线程 %d\n",i);
      hThread = CreateThread(NULL,0,MutexThread,&a[i],0,NULL);//创建线程
      if(hThread == NULL)
      {
         printf("创建线程不成功(%d)\n",GetLastError());
         return;
      }
   }
   Sleep(1000);
   CloseHandle(hMutex);//销毁互斥  
}
DWORD WINAPI MutexThread(LPVOID lpParam)//线程回调函数
{  
   DWORD dwWaitResult;  
   dwWaitResult = WaitForSingleObject(hMutex,INFINITE);//等待互斥量
   switch(dwWaitResult)
   {
      case WAIT_OBJECT_0:  
        Sleep(rand()%100);  
        printf("counter :%d lpPrarm %d\n",dwCounter,*(int *)lpParam);
        dwCounter++;
        if(!ReleaseMutex(hMutex))//离开互斥区域,销毁互斥量CloseHandle
        {  
           printf("释放互斥量错误 %d\n",GetLastError());  
        }
        break;
      default:
        printf("等待超时错误:%d\n",GetLastError());  
        ExitThread(0);  
   }
   return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: