📄 cduelingthreads2.cpp
字号:
#include <stdio.h>
#include "CMcl.h"
unsigned _stdcall ChildThreadProcedure( LPVOID lpcSemaphore) {
// convert parameter to mutex object pointer...
CMclSemaphore *pSemaphore = (CMclSemaphore *)lpcSemaphore;
// save this thread's id...
DWORD dwThreadId = GetCurrentThreadId();
// repeat three times...
for (int n =0; n < 3; n++) {
// wait to acquire the semaphore...
DWORD dwResult = pSemaphore->Wait(INFINITE);
if (dwResult == WAIT_OBJECT_0) {
printf("Thread 0x%08x - acquired the semaphore.\n", dwThreadId);
// hold the semaphore for one-half second and sleep...
Sleep(500);
printf("Thread 0x%08x - releasing the semaphore.\n", dwThreadId);
LONG lPreviousCount;
pSemaphore->Release( 1, &lPreviousCount);
// wait for one-half second before trying again...
Sleep(500);
}
else {
printf("Thread 0x%08x - error calling WaitForSingleObject().\n", dwThreadId);
return 0xFFFFFFFF;
}
}
return 0;
}
int main(void) {
HANDLE hChildThread[3];
// create the semaphore...
CMclSemaphore cSemaphore( 2, 2);
if (cSemaphore.Status() != NO_ERROR) {
printf("Primary thread - error creating semaphore object.\n");
exit(0xFFFFFFFF);
}
// create the child threads...
unsigned uUnusedThreadId;
hChildThread[0] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cSemaphore, 0, &uUnusedThreadId);
hChildThread[1] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cSemaphore, 0, &uUnusedThreadId);
hChildThread[2] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cSemaphore, 0, &uUnusedThreadId);
if (!hChildThread[0] || !hChildThread[1] || !hChildThread[2]) {
printf("Primary thread - error creating child threads.\n");
exit(0xFFFFFFFF);
}
// wait until the child threads have exited...
DWORD dwResult = WaitForMultipleObjects( 3, hChildThread, TRUE, INFINITE);
if (dwResult != WAIT_OBJECT_0) {
printf("Primary thread - error calling WaitForMultipleObjects().\n");
exit(0xFFFFFFFF);
}
// clean up all handles...
CloseHandle(hChildThread[0]);
CloseHandle(hChildThread[1]);
CloseHandle(hChildThread[2]);
// semaphore is cleaned up automatically by the ~CMclSemaphore destructor...
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -