互斥锁的联用

#include <windows.h>
#include <process.h>
#include <wchar.h>

void ReversePrintf(wchar_t *pContent);
unsigned __stdcall TestSemaphore(void *pParams);

struct AsynInfo
{
 wchar_t stringInfo[2][1024];
 int     nUseIndex[2];
 HANDLE  hSemaphore;
 HANDLE  hPrintMutex;
 HANDLE  hSetUseIndexEvent;
};

int _tmain(int argc, _TCHAR* argv[])
{
 AsynInfo testInfo;
 testInfo.hSemaphore = NULL;
 testInfo.nUseIndex[0] = 0;
 testInfo.nUseIndex[1] = 0;

 for(int i = 0; i < 2; i++)
 {
  memset(testInfo.stringInfo[i], 0 ,1024);
 }

 testInfo.hSemaphore =  CreateSemaphore(NULL, 0, 2, "JYYTest");
 testInfo.hPrintMutex = CreateMutex(NULL, FALSE, "testMutex");
 testInfo.hSetUseIndexEvent = CreateEvent(NULL, FALSE, TRUE, "JYYTEST3");
 
 HANDLE hTestThread[5] = {0};
 for(int i = 0; i < 5; i++)
 {
  hTestThread[i] = (HANDLE) _beginthreadex(NULL, 0, TestSemaphore, &testInfo, NULL, NULL);
 }

 ReleaseSemaphore(testInfo.hSemaphore, 2, NULL);

 WaitForMultipleObjects(5, hTestThread, TRUE, -1);
 for(int i = 0; i < 5; i++)
 {
  CloseHandle( hTestThread[i] );;
 }
 CloseHandle(testInfo.hPrintMutex);
 CloseHandle(testInfo.hSemaphore);

 printf("/r/n over /r/n");
 char cTest;
 scanf("%c", &cTest);

 return 0;
}

static nThreadCount = 0;

unsigned __stdcall TestSemaphore(void *pParams)
{
 if (NULL == pParams)
  return 0;
 
 AsynInfo *pAsynInfo = (AsynInfo *)pParams;
 int nThreadID = nThreadCount++;
 HANDLE resourceHandle[2];
 resourceHandle[0] = pAsynInfo->hSemaphore; 
 resourceHandle[1] = pAsynInfo->hSetUseIndexEvent;
 
 for (int i = 0; i < 3; i++)
 {
  WaitForMultipleObjects(2, resourceHandle, TRUE, -1);
  DWORD nFetchIndex = pAsynInfo->nUseIndex[0] == 0 ? 0: 1;
  pAsynInfo->nUseIndex[nFetchIndex] = 1;
  SetEvent(pAsynInfo->hSetUseIndexEvent);

  swprintf(pAsynInfo->stringInfo[nFetchIndex],
     L"the thread is %d, use buffer index is %d /r/n", nThreadID, nFetchIndex);
  WaitForSingleObject(pAsynInfo->hPrintMutex, -1);
  ReversePrintf(pAsynInfo->stringInfo[nFetchIndex]);
  ReleaseMutex(pAsynInfo->hPrintMutex);
  pAsynInfo->nUseIndex[nFetchIndex] = 0;
  ReleaseSemaphore(pAsynInfo->hSemaphore, 1, NULL);

  Sleep(1);
 }
 
 return 1;
}

void ReversePrintf(wchar_t *pContent)
{
 if (!pContent)
  return;
 
 wcsrev(pContent);
 wprintf(pContent);
 Sleep(500);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值