• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            C++ Programmer's Cookbook

            {C++ 基礎(chǔ)} {C++ 高級} {C#界面,C++核心算法} {設(shè)計模式} {C#基礎(chǔ)}

            C++多線程(七)

            多線程同步之Semaphore (主要用來解決生產(chǎn)者/消費者問題)

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

            為了正確地說明這個問題,讓我們來看一看應(yīng)用程序是如何使用信標的。比如說,我正在開發(fā)一個服務(wù)器進程,在這個進程中,我已經(jīng)分配了一個能夠用來存放客戶機請求的緩沖區(qū)。我對緩沖區(qū)的大小進行了硬編碼,這樣它每次最多能夠存放5個客戶機請求。如果5個請求尚未處理完畢時,一個新客戶機試圖與服務(wù)器進行聯(lián)系,那么這個新客戶機的請求就會被拒絕,并出現(xiàn)一個錯誤,指明服務(wù)器現(xiàn)在很忙,客戶機應(yīng)該過些時候重新進行聯(lián)系。當我的服務(wù)器進程初始化時,它創(chuàng)建一個線程池,里面包含5個線程,每個線程都準備在客戶機請求到來時對它進行處理。

            開始時,沒有客戶機提出任何請求,因此我的服務(wù)器不允許線程池中的任何線程成為可調(diào)度線程。但是,如果3個客戶機請求同時到來,那么線程池中應(yīng)該有3個線程處于可調(diào)度狀態(tài)。使用信標,就能夠很好地處理對資源的監(jiān)控和對線程的調(diào)度,最大資源數(shù)量設(shè)置為5,因為這是我進行硬編碼的緩沖區(qū)的大小。當前資源數(shù)量最初設(shè)置為0,因為沒有客戶機提出任何請求。當客戶機的請求被接受時,當前資源數(shù)量就遞增,當客戶機的請求被提交給服務(wù)器的線程池時,當前資源數(shù)量就遞減。

            信標的使用規(guī)則如下:

            • 如果當前資源的數(shù)量大于0,則發(fā)出信標信號。

            • 如果當前資源數(shù)量是0,則不發(fā)出信標信號。

            • 系統(tǒng)決不允許當前資源的數(shù)量為負值。

            • 當前資源數(shù)量決不能大于最大資源數(shù)量。

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

            二 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.

            三 實例
            #include <windows.h>
            #include 
            <stdio.h>

            #define MAX_SEM_COUNT 6
            #define THREADCOUNT 12

            HANDLE ghSemaphore;

            DWORD WINAPI ThreadProc( LPVOID );

            void main()
            {
                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\n", GetLastError());
                    
            return;
                }


                
            // 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\n", GetLastError());
                        
            return;
                    }

                }


                
            // 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);
            }


            DWORD WINAPI ThreadProc( LPVOID lpParam )
            {
                DWORD dwWaitResult; 
                BOOL bContinue
            =TRUE;

                
            while(bContinue)
                
            {
                    
            // Try to enter the semaphore gate.

                    dwWaitResult 
            = WaitForSingleObject( 
                        ghSemaphore,   
            // handle to semaphore
                        3L);           // zero-second time-out interval

                    
            switch (dwWaitResult) 
                    

                        
            // The semaphore object was signaled.
                        case WAIT_OBJECT_0: 
                            
            // TODO: Perform task
                            printf("Thread %d: wait succeeded\n", GetCurrentThreadId());
                            bContinue
            =FALSE;            

                            
            // Simulate thread spending time on task
                            Sleep(5);

                            
            for(int x = 0; x< 10; x++)
                                printf(
            "Thread %d task!\n",GetCurrentThreadId());

                            
            // Relase 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\n", GetLastError());
                            }

                            
            break

                        
            // The semaphore was nonsignaled, so a time-out occurred.
                        case WAIT_TIMEOUT: 
                            printf(
            "Thread %d: wait timed out\n", GetCurrentThreadId());
                            
            break
                    }

                }

                
            return TRUE;
            }


            四 參考 http://msdn2.microsoft.com/en-us/library/ms686946.aspx

            posted on 2007-07-30 15:40 夢在天涯 閱讀(3405) 評論(1)  編輯 收藏 引用 所屬分類: CPlusPlus

            評論

            # re: C++多線程(七) 2007-07-30 15:54 夢在天涯

            多線程同步msdn :http://msdn2.microsoft.com/en-us/library/ms686353.aspx  回復(fù)  更多評論   

            公告

            EMail:itech001#126.com

            導航

            統(tǒng)計

            • 隨筆 - 461
            • 文章 - 4
            • 評論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1804430
            • 排名 - 5

            最新評論

            閱讀排行榜

            日韩人妻无码一区二区三区久久99| 天天综合久久一二三区| 中文字幕久久精品| 久久99精品九九九久久婷婷| www久久久天天com| 久久99精品国产自在现线小黄鸭| 国产精品99久久久精品无码| 看全色黄大色大片免费久久久| 久久国产精品一区| 久久精品亚洲精品国产欧美| 久久久久亚洲?V成人无码| 久久免费国产精品| 日韩精品久久久久久久电影| 综合久久精品色| 久久精品国产久精国产一老狼| 色天使久久综合网天天| 亚洲国产精品无码久久98| 久久久久久夜精品精品免费啦| 精品蜜臀久久久久99网站| 久久久久一区二区三区| 91久久香蕉国产熟女线看| 精品人妻伦九区久久AAA片69| 理论片午午伦夜理片久久| 亚洲国产成人久久笫一页| 亚洲AV日韩精品久久久久久久 | 国产毛片欧美毛片久久久| 欧洲人妻丰满av无码久久不卡| 国产Av激情久久无码天堂| 久久国产成人亚洲精品影院| 久久天天婷婷五月俺也去| 亚洲精品无码久久久久去q| 久久精品国产半推半就| 亚洲国产成人精品无码久久久久久综合 | 久久美女人爽女人爽| 久久精品中文字幕一区| 亚洲狠狠婷婷综合久久久久| 国产69精品久久久久99尤物| 久久久噜噜噜久久中文字幕色伊伊 | 午夜精品久久久久久影视777| 国产麻豆精品久久一二三| 日本精品久久久久影院日本|