• <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++ 高級(jí)} {C#界面,C++核心算法} {設(shè)計(jì)模式} {C#基礎(chǔ)}

            C++多線程(七)

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

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

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

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

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

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

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

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

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

            當(dāng)使用信標(biāo)時(shí),不要將信標(biāo)對(duì)象的使用數(shù)量與它的當(dāng)前資源數(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.

            三 實(shí)例
            #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 夢(mèng)在天涯 閱讀(3407) 評(píng)論(1)  編輯 收藏 引用 所屬分類: CPlusPlus

            評(píng)論

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

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

            公告

            EMail:itech001#126.com

            導(dǎo)航

            統(tǒng)計(jì)

            • 隨筆 - 461
            • 文章 - 4
            • 評(píng)論 - 746
            • 引用 - 0

            常用鏈接

            隨筆分類

            隨筆檔案

            收藏夾

            Blogs

            c#(csharp)

            C++(cpp)

            Enlish

            Forums(bbs)

            My self

            Often go

            Useful Webs

            Xml/Uml/html

            搜索

            •  

            積分與排名

            • 積分 - 1807518
            • 排名 - 5

            最新評(píng)論

            閱讀排行榜

            久久国产免费直播| 久久香蕉国产线看观看精品yw| 性高湖久久久久久久久| 少妇内射兰兰久久| 97精品国产91久久久久久| 国产成人99久久亚洲综合精品| 精品久久久久一区二区三区 | 伊人久久大香线蕉亚洲五月天| 久久天天躁狠狠躁夜夜躁2014| 人妻精品久久久久中文字幕69| 99久久久久| 久久久久久久97| 99久久无码一区人妻| 国产欧美久久久精品影院| 99久久精品费精品国产一区二区| 久久综合九色综合久99| 久久久久亚洲AV无码专区体验| 久久久久亚洲av成人无码电影 | 久久福利资源国产精品999| 国产成人精品白浆久久69| 中文字幕无码久久精品青草| 精品久久久久久国产潘金莲| 2020国产成人久久精品| 久久久久国产视频电影| 久久人人爽人人爽人人AV东京热| 国产成人久久精品二区三区| 久久久久久国产精品免费无码| 久久久久亚洲AV综合波多野结衣 | 久久无码国产专区精品| 亚洲国产精品一区二区久久| 激情伊人五月天久久综合 | 精品久久久久久久无码| 久久精品国产2020| 久久精品国产99国产精品亚洲| 久久综合日本熟妇| 人妻中文久久久久| 久久综合精品国产一区二区三区| 欧美精品一本久久男人的天堂| WWW婷婷AV久久久影片| 久久婷婷五月综合色奶水99啪| 久久久久久久久久久久久久|