#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);
}