// Try to enter the semaphore gate. while(1) { dwWaitResult = WaitForSingleObject( hSemaphore, // handle to semaphore 100L); // zero-second time-out interval switch (dwWaitResult) { // The semaphore object was signaled. case WAIT_OBJECT_0: // OK to open another window. cThreadCont++; printf("[OK]Open another thread[%d]\n", cThreadCont); AfxBeginThread(thread_func, NULL); break; // Semaphore was nonsignaled, so a time-out occurred. case WAIT_TIMEOUT: // Cannot open another window. continue; break; } }而后在线程中 UINT thread_func(LPVOID lpParam) { //处理...... //结束处理 if (!ReleaseSemaphore( hSemaphore, // handle to semaphore 1, // increase count by one NULL) ) // not interested in previous count { // Deal with the error. printf("[*]Release Semaphore Error!\n"); return -1; } cThreadCont --; return 0; }
NULL, // no security attributes
0, // 这个初始值设为0
cMax, // maximum count
NULL); // unnamed semaphore
而后有一个管理线程部分
DWORD dwWaitResult;
// Try to enter the semaphore gate. while(1)
{
dwWaitResult = WaitForSingleObject(
hSemaphore, // handle to semaphore
100L); // zero-second time-out interval switch (dwWaitResult) {
// The semaphore object was signaled.
case WAIT_OBJECT_0:
// OK to open another window.
cThreadCont++;
printf("[OK]Open another thread[%d]\n", cThreadCont);
AfxBeginThread(thread_func, NULL);
break;
// Semaphore was nonsignaled, so a time-out occurred.
case WAIT_TIMEOUT:
// Cannot open another window.
continue;
break;
}
}而后在线程中
UINT thread_func(LPVOID lpParam)
{
//处理...... //结束处理
if (!ReleaseSemaphore(
hSemaphore, // handle to semaphore
1, // increase count by one
NULL) ) // not interested in previous count
{
// Deal with the error.
printf("[*]Release Semaphore Error!\n");
return -1;
}
cThreadCont --;
return 0;
}