스레드 동기화 Semaphore

4069 단어 Windows

스레드 동기화 신호량


Semaphore
신호량.
그것은 값이 0보다 크면 신호량 대상이 이미 전송된 상태를 유지하는 계수를 유지한다.일반적으로 사용 가능한 자원의 개수를 수치로 표시합니다.
WaitForSingleObject()는 신호량을 1로 줄입니다.ReleaseSemaphore()는 신호량을 1씩 증가시킵니다.
//Semaphore
//this example is from msdn
#include 
#include 

#define MAX_SEM_COUNT 6
#define THREADCOUNT 8

HANDLE ghSemaphore;

DWORD WINAPI ThreadProc( LPVOID );

int main( void )
{
    HANDLE aThread[THREADCOUNT];
    DWORD ThreadID;
    int i;

    // Create a semaphore with initial and max counts of MAX_SEM_COUNT

    ghSemaphore = CreateSemaphore( 
        NULL,           // default security attributes
        MAX_SEM_COUNT,  // initial count
        MAX_SEM_COUNT,  // maximum count
        NULL);          // unnamed semaphore
    if (ghSemaphore == NULL) 
    {
        printf("CreateSemaphore error: %d
", GetLastError()); return 1; } // Create worker threads for( i=0; i < THREADCOUNT; i++ ){ aThread[i] = CreateThread( NULL, // default security attributes 0, // default stack size (LPTHREAD_START_ROUTINE) ThreadProc, NULL, // no thread function arguments 0, // default creation flags &ThreadID); // receive thread identifier if( aThread[i] == NULL ){ printf("CreateThread error: %d
", GetLastError()); return 1; } } // Wait for all threads to terminate WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE); // Close thread and semaphore handles for( i=0; i < THREADCOUNT; i++ ) CloseHandle(aThread[i]); CloseHandle(ghSemaphore); return 0; } DWORD WINAPI ThreadProc( LPVOID lpParam ) { // lpParam not used in this example UNREFERENCED_PARAMETER(lpParam); DWORD dwWaitResult; BOOL bContinue=TRUE; while(bContinue) { // Try to enter the semaphore gate. dwWaitResult = WaitForSingleObject( ghSemaphore, // handle to semaphore 1L); // zero-second time-out interval switch (dwWaitResult) { // The semaphore object was signaled. case WAIT_OBJECT_0: // TODO: Perform task printf("Thread %d: wait succeeded
", GetCurrentThreadId()); bContinue=FALSE; // Simulate thread spending time on task Sleep(5); // Release the semaphore when task is finished if (!ReleaseSemaphore( ghSemaphore, // handle to semaphore 1, // increase count by one NULL) ) // not interested in previous count { printf("ReleaseSemaphore error: %d
", GetLastError()); } break; // The semaphore was nonsignaled, so a time-out occurred. case WAIT_TIMEOUT: printf("Thread %d: wait timed out
", GetCurrentThreadId()); break; } } return TRUE; } /* Thread 7752: wait succeeded Thread 9520: wait succeeded Thread 10852: wait succeeded Thread 5352: wait succeeded Thread 8164: wait succeeded Thread 10060: wait succeeded Thread 4800: wait timed out Thread 4516: wait timed out Thread 4516: wait timed out Thread 4800: wait timed out Thread 4800: wait timed out Thread 4800: wait succeeded Thread 4516: wait timed out Thread 4516: wait succeeded . . . */

분석:
신호량 6, MAXSEM_COUNT, 신호량을 사용하는 라인은 8,THREADCOUNT이고main 함수 라인은 포함되지 않습니다.그래서 처음 6개의 만들어진 스레드WaitForSingleObject()가 WAIT 로 되돌아옵니다.OBJECT_0, 막히지 않습니다.다음 스레드 WaitForSingleObject()는 WAIT 로 반환됩니다.TIMEOUT, 다른 P 작업이 성공한 스레드Sleep(5)을 기다린 후 V 조작을 해야 WAIT 를 획득할 수 있습니다OBJECT_0은(는) 값을 반환합니다.8개의 ThreadProc 스레드가 실행되고 주 함수에서WaitForMultipleObjects () 함수가 되돌아옵니다.

좋은 웹페이지 즐겨찾기