多線程(C++)同步Semaphore

多線程同步之Semaphore (主要解決生產者消費者問題)

一 信標Semaphore
信標內核對象用於對資源進行計數。它們與所有內核對象一樣,包含一個使用數量,但是它們也包含另外兩個帶符號的3 2位值,一個是最大資源數量,一個是當前資源數量。最大資源數量用於標識信標能夠控制的資源的最大數量,而當前資源數量則用於標識當前可以使用的資源的數量。

爲了正確地說明這個問題,讓我們來看一看應用程序是如何使用信標的。比如說,我正在開發一個服務器進程,在這個進程中,我已經分配了一個能夠用來存 放客戶機請求的緩衝區。我對緩衝區的大小進行了硬編碼,這樣它每次最多能夠存放5個客戶機請求。如果5個請求尚未處理完畢時,一個新客戶機試圖與服務器進 行聯繫,那麼這個新客戶機的請求就會被拒絕,並出現一個錯誤,指明服務器現在很忙,客戶機應該過些時候重新進行聯繫。當我的服務器進程初始化時,它創建一 個線程池,裏面包含5個線程,每個線程都準備在客戶機請求到來時對它進行處理。

開始時,沒有客戶機提出任何請求,因此我的服務器不允許線程池中的任何線程成爲可調度線程。但是,如果3個客戶機請求同時到來,那麼線程池中應該有 3個線程處於可調度狀態。使用信標,就能夠很好地處理對資源的監控和對線程的調度,最大資源數量設置爲5,因爲這是我進行硬編碼的緩衝區的大小。當前資源 數量最初設置爲0,因爲沒有客戶機提出任何請求。當客戶機的請求被接受時,當前資源數量就遞增,當客戶機的請求被提交給服務器的線程池時,當前資源數量就 遞減。

信標的使用規則如下:

? 如果當前資源的數量大於0,則發出信標信號。

? 如果當前資源數量是0,則不發出信標信號。

? 系統決不允許當前資源的數量爲負值。

? 當前資源數量決不能大於最大資源數量。

當使用信標時,不要將信標對象的使用數量與它的當前資源數量混爲一談。

二 API

Semaphore function Description
CreateSemaphore Creates or opens a named or unnamed semaphore object.
CreateSemaphoreEx Creates or opens a named or unnamed semaphore object and returns a handle to the object.
OpenSemaphore Opens an existing named semaphore object.
ReleaseSemaphore Increases the count of the specified semaphore object by a specified amount.

三 實例
多線程(C++)同步Semaphore#include <windows.h>
多線程(C++)同步Semaphore#include 
<stdio.h>
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore
#define MAX_SEM_COUNT 6
多線程(C++)同步Semaphore
#define THREADCOUNT 12
多線程(C++)同步Semaphore
多線程(C++)同步SemaphoreHANDLE ghSemaphore;
多線程(C++)同步Semaphore
多線程(C++)同步SemaphoreDWORD WINAPI ThreadProc( LPVOID );
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore
void main()
多線程(C++)同步Semaphore
{
多線程(C++)同步Semaphore    HANDLE aThread[THREADCOUNT];
多線程(C++)同步Semaphore    DWORD ThreadID;
多線程(C++)同步Semaphore    
int i;
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore    
// Create a semaphore with initial and max counts of MAX_SEM_COUNT
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore    ghSemaphore 
= CreateSemaphore( 
多線程(C++)同步Semaphore        NULL,           
// default security attributes
多線程(C++)同步Semaphore
        MAX_SEM_COUNT,  // initial count
多線程(C++)同步Semaphore
        MAX_SEM_COUNT,  // maximum count
多線程(C++)同步Semaphore
        NULL);          // unnamed semaphore
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore    
if (ghSemaphore == NULL) 
多線程(C++)同步Semaphore    
{
多線程(C++)同步Semaphore        printf(
"CreateSemaphore error: %d\n", GetLastError());
多線程(C++)同步Semaphore        
return;
多線程(C++)同步Semaphore    }

多線程(C++)同步Semaphore
多線程(C++)同步Semaphore    
// Create worker threads
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore    
for( i=0; i < THREADCOUNT; i++ )
多線程(C++)同步Semaphore    
{
多線程(C++)同步Semaphore        aThread[i] 
= CreateThread( 
多線程(C++)同步Semaphore                     NULL,       
// default security attributes
多線程(C++)同步Semaphore
                     0,          // default stack size
多線程(C++)同步Semaphore
                     (LPTHREAD_START_ROUTINE) ThreadProc, 
多線程(C++)同步Semaphore                     NULL,       
// no thread function arguments
多線程(C++)同步Semaphore
                     0,          // default creation flags
多線程(C++)同步Semaphore
                     &ThreadID); // receive thread identifier
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore        
if( aThread[i] == NULL )
多線程(C++)同步Semaphore        
{
多線程(C++)同步Semaphore            printf(
"CreateThread error: %d\n", GetLastError());
多線程(C++)同步Semaphore            
return;
多線程(C++)同步Semaphore        }

多線程(C++)同步Semaphore    }

多線程(C++)同步Semaphore
多線程(C++)同步Semaphore    
// Wait for all threads to terminate
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore    WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore    
// Close thread and semaphore handles
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore    
for( i=0; i < THREADCOUNT; i++ )
多線程(C++)同步Semaphore        CloseHandle(aThread[i]);
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore    CloseHandle(ghSemaphore);
多線程(C++)同步Semaphore}

多線程(C++)同步Semaphore
多線程(C++)同步SemaphoreDWORD WINAPI ThreadProc( LPVOID lpParam )
多線程(C++)同步Semaphore
{
多線程(C++)同步Semaphore    DWORD dwWaitResult; 
多線程(C++)同步Semaphore    BOOL bContinue
=TRUE;
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore    
while(bContinue)
多線程(C++)同步Semaphore    
{
多線程(C++)同步Semaphore        
// Try to enter the semaphore gate.
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore        dwWaitResult 
= WaitForSingleObject( 
多線程(C++)同步Semaphore            ghSemaphore,   
// handle to semaphore
多線程(C++)同步Semaphore
            3L);           // zero-second time-out interval
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore        
switch (dwWaitResult) 
多線程(C++)同步Semaphore        

多線程(C++)同步Semaphore            
// The semaphore object was signaled.
多線程(C++)同步Semaphore
            case WAIT_OBJECT_0: 
多線程(C++)同步Semaphore                
// TODO: Perform task
多線程(C++)同步Semaphore
                printf("Thread %d: wait succeeded\n", GetCurrentThreadId());
多線程(C++)同步Semaphore                bContinue
=FALSE;            
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore                
// Simulate thread spending time on task
多線程(C++)同步Semaphore
                Sleep(5);
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore                
for(int x = 0; x< 10; x++)
多線程(C++)同步Semaphore                    printf(
"Thread %d task!\n",GetCurrentThreadId());
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore                
// Relase the semaphore when task is finished
多線程(C++)同步Semaphore

多線程(C++)同步Semaphore                
if (!ReleaseSemaphore( 
多線程(C++)同步Semaphore                        ghSemaphore,  
// handle to semaphore
多線程(C++)同步Semaphore
                        1,            // increase count by one
多線程(C++)同步Semaphore
                        NULL) )       // not interested in previous count
多線程(C++)同步Semaphore
                {
多線程(C++)同步Semaphore                    printf(
"ReleaseSemaphore error: %d\n", GetLastError());
多線程(C++)同步Semaphore                }

多線程(C++)同步Semaphore                
break
多線程(C++)同步Semaphore
多線程(C++)同步Semaphore            
// The semaphore was nonsignaled, so a time-out occurred.
多線程(C++)同步Semaphore
            case WAIT_TIMEOUT: 
多線程(C++)同步Semaphore                printf(
"Thread %d: wait timed out\n", GetCurrentThreadId());
多線程(C++)同步Semaphore                
break
多線程(C++)同步Semaphore        }

多線程(C++)同步Semaphore    }

多線程(C++)同步Semaphore    
return TRUE;
多線程(C++)同步Semaphore}
發佈了82 篇原創文章 · 獲贊 22 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章