#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);
}
本文展示了一个使用Windows API实现的多线程程序案例,通过Semaphore(信号量)、Mutex(互斥锁)和Event(事件)来协调多个线程间的资源访问与执行顺序。具体涉及如何创建线程、使用信号量限制同时访问资源的线程数量、利用互斥锁确保打印操作的原子性,以及借助事件对象更新资源使用的状态。
1101

被折叠的 条评论
为什么被折叠?



