DWORD WINAPI TestThreadPool(PVOID pContext);
CRITICAL_SECTION g_cs;
int _tmain(int argc, _TCHAR* argv[])
{
InitializeCriticalSection(&g_cs);
SECURITY_ATTRIBUTES sa;
sa.bInheritHandle = TRUE;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
sa.lpSecurityDescriptor = NULL;
HANDLE hSemaphore = CreateSemaphoreW(&sa, 0 ,1, L"jyytet");
for (int i = 0; i < 10; i++)
{
QueueUserWorkItem(TestThreadPool, L"Hello World", WT_EXECUTEDEFAULT);
}
QueueUserWorkItem(TestThreadPool, L"Finish", WT_EXECUTEDEFAULT);
WaitForSingleObject(hSemaphore, -1);
CloseHandle(hSemaphore);
hSemaphore = NULL;
DeleteCriticalSection(&g_cs);
wprintf(L"Game over /r/n");
getchar();
return 0;
}
DWORD WINAPI TestThreadPool(PVOID pContext)
{
if (NULL == pContext)
return 0;
EnterCriticalSection(&g_cs);
wchar_t *pPrintf = (wchar_t *) pContext;
wprintf(L"%s /r/n", pPrintf);
Sleep(1000);
if (wcscmp(pPrintf, L"Finish") == 0)
{
HANDLE hSemaphore = OpenSemaphoreW(SEMAPHORE_ALL_ACCESS, FALSE, L"jyytet");
assert(hSemaphore != NULL);
ReleaseSemaphore(hSemaphore, 1, NULL);
CloseHandle(hSemaphore);
}
LeaveCriticalSection(&g_cs);
return 1;
}
本文通过一个具体的示例介绍了如何使用Windows线程池API来调度任务,并利用信号量与临界区进行线程间的同步。示例中创建了一个可继承的信号量对象用于等待所有线程完成工作,并通过QueueUserWorkItem函数将任务加入到线程池。
1330

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



