?? cduelingthreads1.cpp
字號:
#include <stdio.h>
#include "CMcl.h"
unsigned _stdcall ChildThreadProcedure( LPVOID lpcMutex) {
// convert parameter to mutex object pointer...
CMclMutex *pMutex = (CMclMutex *)lpcMutex;
// save this thread's id...
DWORD dwThreadId = GetCurrentThreadId();
// repeat three times...
for (int n =0; n < 3; n++) {
// wait to acquire the mutex...
DWORD dwResult = pMutex->Wait(INFINITE);
if (dwResult == WAIT_OBJECT_0) {
printf("Thread 0x%08x - acquired the mutex.\n", dwThreadId);
// hold the mutex for one-half second and sleep...
Sleep(500);
printf("Thread 0x%08x - releasing the mutex.\n", dwThreadId);
pMutex->Release();
// wait for one-half second before trying again...
Sleep(500);
}
else {
printf("Thread 0x%08x - error calling CMclMutex::Wait().\n", dwThreadId);
return 0xFFFFFFFF;
}
}
return 0;
}
int main(void) {
// create the mutex...
CMclMutex cMutex;
if (cMutex.Status() != NO_ERROR) {
printf("Primary thread - error creating mutex.\n");
exit(0xFFFFFFFF);
}
// create the child threads, passing a pointer to the mutex object...
HANDLE hChildThread[3];
unsigned uUnusedThreadId;
hChildThread[0] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cMutex, 0, &uUnusedThreadId);
hChildThread[1] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cMutex, 0, &uUnusedThreadId);
hChildThread[2] = (HANDLE)_beginthreadex( NULL, 0, ChildThreadProcedure, (void*) &cMutex, 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]);
// mutex is cleaned up automatically by the ~CMclMutex destructor...
return 0;
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -