多线程--信号量Semaphore

来源:互联网 发布:实现即时通讯的php文件 编辑:程序博客网 时间:2024/05/16 10:33



#include "stdafx.h"#include <stdio.h>  #include <process.h>  #include <windows.h>  long g_nNum;  unsigned int __stdcall Fun(void *pPM);  const int THREAD_NUM = 10;  HANDLE g_hMutex;HANDLE g_hSem;//信号量无所有权概念,可用于同步int main()  {  g_hSem = CreateSemaphore(NULL,0,1,NULL);//信号量总数1,只允许一个线程同时访问。//初值设置为0,该程序中让主线程等着。g_hMutex = CreateMutex(NULL,FALSE,NULL);HANDLE  handle[THREAD_NUM];   g_nNum = 0;   int i = 0;  while (i < THREAD_NUM)   {  handle[i] = (HANDLE)_beginthreadex(NULL, 0, Fun, &i, 0, NULL);  WaitForSingleObject(g_hSem, INFINITE); //等待信号量>0。执行后,信号量-1i++;  }  WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);  CloseHandle(g_hSem);CloseHandle(g_hMutex);for (i = 0; i < THREAD_NUM; i++)  CloseHandle(handle[i]);  return 0;  }  unsigned int __stdcall Fun(void *pPM)  {  int nThreadNum = *(int *)pPM;ReleaseSemaphore(g_hSem,1,NULL);//执行后,信号量+1Sleep(50);//some work should to do  WaitForSingleObject(g_hMutex,INFINITE);g_nNum++;  Sleep(0);//some work should to do  printf("线程编号为%d  全局资源值为%d\n", nThreadNum, g_nNum);  ReleaseMutex(g_hMutex);return 0;  }  

0 0