青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品

C++ Programmer's Cookbook

{C++ 基礎} {C++ 高級} {C#界面,C++核心算法} {設計模式} {C#基礎}

C++多線程(三)

多線程同步之Critical Sections(功能與Mutex相同,保證某一時刻只有一個線程能夠訪問共享資源,但是不是內核對象,所以訪問速度要比Mutex快,但是增沒有等待超時的功能,所以有可能會導致死鎖,使用時可以根據實際的情況選擇其一

一 Critical Sections

1) 因為Critical Sections不是內核對象,所以只能用來統一進程內線程間的同步,不能用來多個不同進程間的線程的同步。

2) 如果在Critical Sections中間突然程序crash或是exit而沒有調用LeaveCriticalSection,則結果是改線程所對應的內核不能被釋放,該線程成為死線程。

3) 要比其他的內核對象的速度要快。

二 使用CriticalSections的簡單實例,Stack在push的時候可以分為3個步驟,看下面的代碼,但是如果在第2步后此線程中斷切換到其他的線程,其他的線程push后再返回執行時,此線程繼續執行,這樣有可能剛才其他線程push就會被覆蓋了,在stack里找不到了。(下面的代碼在debug下使用了CriticalSection,release下可能有問題)

#include <windows.h>
#include 
<process.h>
#include 
<stdio.h>
/////////////////////////////////////////////
//stack:
struct Node 
{
    
struct Node *next; 
    
int data; 
}

struct Stack 

    
struct Node *head; 
#ifdef _DEBUG
    CRITICAL_SECTION critical_sec; 
#endif

    Stack()
    
{
        head 
= NULL;
#ifdef _DEBUG
        InitializeCriticalSection(
&critical_sec);
#endif
    }

    
~Stack()
    
{        
        
if(head != NULL)        
        
{
            
if(NULL == head->next)
            
{                
                delete head;
                head 
= NULL;
            }

            
else
            
{
                Node 
*= head;
                Node 
*= head->next;

                
while(q != NULL)
                
{                    
                    delete p;
                    p 
= q;
                    q 
= q->next;
                }
;                
                delete p;
                p 
= NULL;
            }
    
        }

#ifdef _DEBUG
        DeleteCriticalSection(
&critical_sec);
#endif
    }

    
void Push (int num) 
    

        
//enter critical section, add a new node and then     
#ifdef _DEBUG
        EnterCriticalSection (
&critical_sec);
#endif
        Node 
* node = new Node();
        node
->next = head;
        node
->data = num;
        head 
= node;  
        printf(
"Stack:%d\n",num);
        
//leave critical section 
#ifdef _DEBUG
        LeaveCriticalSection (
&critical_sec);
#endif
    }
 
    
int Pop () 
    

#ifdef _DEBUG
        EnterCriticalSection (
&critical_sec);
#endif
        
int result = 0;
        
if(head!= NULL)
        
{
            result 
= head->data;
            
if(head->next != NULL)
            
{
                Node 
*temp = head->next; 
                delete head;
                head 
= temp;
            }

            
else
                head 
= NULL;
        }
    
#ifdef _DEBUG
        LeaveCriticalSection (
&critical_sec); 
#endif
        
return result; 
    }

}
;

//////////////////////////////////////////////////////
//test:
unsigned  __stdcall Thread1(void * pVoid)
{
    Stack 
*stack = ((Stack*)pVoid);
    
for(int i = 200; i<220;++i)
    
{
        stack
->Push(i);
    }

    
return 1;        
}

unsigned __stdcall Thread2(
void *pVoid)
{
    Stack 
*stack = ((Stack*)pVoid);
    
for(int i = 0; i<20++i)
    
{
        stack
->Push(i);        
    }

    
return 1;
}

int main()

    Stack stack;
    stack.Push(
1000);
    stack.Push(
1000);

    HANDLE   hth1;
    unsigned  uiThread1ID;

    hth1 
= (HANDLE)_beginthreadex( NULL,         // security
        0,            // stack size
        Thread1,
        (
void*)&stack,           // arg list
        CREATE_SUSPENDED,  // so we can later call ResumeThread()
        &uiThread1ID );

    
if ( hth1 == 0 )
        printf(
"Failed to create thread 1\n");

    DWORD   dwExitCode;

    GetExitCodeThread( hth1, 
&dwExitCode );  // should be STILL_ACTIVE = 0x00000103 = 259
    printf( "initial thread 1 exit code = %u\n", dwExitCode );



    HANDLE   hth2;
    unsigned  uiThread2ID;

    hth2 
= (HANDLE)_beginthreadex( NULL,         // security
        0,            // stack size
        Thread2,
        (
void*)&stack,           // arg list
        CREATE_SUSPENDED,  // so we can later call ResumeThread()
        &uiThread2ID );

    
if ( hth2 == 0 )
        printf(
"Failed to create thread 2\n");

    GetExitCodeThread( hth2, 
&dwExitCode );  // should be STILL_ACTIVE = 0x00000103 = 259
    printf( "initial thread 2 exit code = %u\n", dwExitCode );  

    ResumeThread( hth1 );   
    ResumeThread( hth2 );

    WaitForSingleObject( hth1, INFINITE );
    WaitForSingleObject( hth2, INFINITE );

    GetExitCodeThread( hth1, 
&dwExitCode );
    printf( 
"thread 1 exited with code %u\n", dwExitCode );

    GetExitCodeThread( hth2, 
&dwExitCode );
    printf( 
"thread 2 exited with code %u\n", dwExitCode );

    CloseHandle( hth1 );
    CloseHandle( hth2 );    

    printf(
"Primary thread terminating.\n");
}


三 對Critical Section的封裝:
//////////////////////////////////////////////////////
// 方法一: Lock中的CritSect成員變量必須是引用類型。
class CritSect
{
public:
    friend 
class Lock;
    CritSect() 
{ InitializeCriticalSection(&_critSection); }
    
~CritSect() { DeleteCriticalSection(&_critSection); }
private:
    
void Acquire(){EnterCriticalSection(&_critSection);}
    
void Release(){LeaveCriticalSection(&_critSection);}

    CRITICAL_SECTION _critSection;
}
;

class Lock
{
public:
     Lock(CritSect
& critSect):_critSect(critSect) {    _critSect.Acquire(); }
     
~Lock(){_critSect.Release();}
private:
    CritSect
& _critSect;
}
;

//////////////////////////////////////////////////////
//方法二:
// MT-exclusive lock
class CLock {
public:
    CLock()             
{ InitializeCriticalSection (&m_criticalSection); }
    
void Lock ()        { EnterCriticalSection      (&m_criticalSection); }
    
void Unlock ()      { LeaveCriticalSection      (&m_criticalSection); }
    
virtual ~CLock()    { DeleteCriticalSection     (&m_criticalSection); }
private:
    CRITICAL_SECTION                    m_criticalSection;
}
;


// Scoped MT-exclusive lock
class CScopedLocker {
public:
    CScopedLocker (CLock 
* t) : m_lock (t)      { m_lock->Lock();   }
    
~CScopedLocker()                            { m_lock->Unlock(); }
private:
    CLock 
*                             m_lock;
}
;


對上面的2中封裝的調用都比較簡單,都是只有2行代碼。
CritSect sect;
Lock lock(sect);

CLock t;
CSCopedLocker st(&t);

下面的對封裝的測試代碼,保證了對g_n全局變量在線程1操作結束后線程2才可以操作。(下面的代碼因為對全局變量同步,所以需要申明含有CRITICAL_SECTION的類為全局)

#include<windows.h>
#include
<iostream>
using namespace std;

//////////////////////////////////////////////////////
// ·½·¨Ò»£º

class CritSect
{
public:
    friend 
class Lock;
    CritSect() 
{ InitializeCriticalSection(&_critSection); }
    
~CritSect() { DeleteCriticalSection(&_critSection); }
private:
    
void Acquire(){EnterCriticalSection(&_critSection);}
    
void Release(){LeaveCriticalSection(&_critSection);}

    CRITICAL_SECTION _critSection;
}
;

class Lock
{
public:
     Lock(CritSect
& critSect):_critSect(critSect) {    _critSect.Acquire(); }
     
~Lock(){_critSect.Release();}
private:
    CritSect
& _critSect;
}
;

//////////////////////////////////////////////////////
//·½·¨¶þ£º

// MT-exclusive lock
class CLock {
public:
    CLock()             
{ InitializeCriticalSection (&m_criticalSection); }
    
void Lock ()        { EnterCriticalSection      (&m_criticalSection); }
    
void Unlock ()      { LeaveCriticalSection      (&m_criticalSection); }
    
virtual ~CLock()    { DeleteCriticalSection     (&m_criticalSection); }
private:
    CRITICAL_SECTION                    m_criticalSection;
}
;


// Scoped MT-exclusive lock
class CScopedLocker {
public:
    CScopedLocker (CLock 
* t) : m_lock (t)      { m_lock->Lock();   }
    
~CScopedLocker()                            { m_lock->Unlock(); }
private:
    CLock 
*                             m_lock;
}
;

// ¶ÔÈ«¾ÖµÄ±äÁ¿£¬Ê¹ÓÃCritical Section
// Declare the global variable
static int  g_n;
CritSect sect;
//CLock t;



////////Thread One Function///////////////////
UINT ThreadOne(LPVOID lParam)
{
    
    Lock 
lock(sect);    
    
//CScopedLocker st(&t);
    
    
for(int i=0;i<100;i++)
    
{
        g_n
++;
        cout 
<< "Thread 1: " << g_n << "\n";
    }
        
    
// return the thread
    return 0;
}



////////Thread Two Function///////////////////
UINT ThreadTwo(LPVOID lParam)
{


    Lock 
lock(sect);
    
//CScopedLocker st(&t);

    
for(int i=300;i<400;i++)
    
{
        g_n
++;
        cout 
<< "Thread 2: "<< g_n << "\n";
    }


    
// return the thread
    return 0;
}



int main()
{

    
// Create the array of Handle
    HANDLE hThrd[2];    
    
//Thread ID's
    DWORD IDThread1, IDThread2;


    
// Create thredas use CreateThread function with NULL Security
    hThrd[0= CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadOne,(LPVOID)NULL,0,&IDThread1);       
    hThrd[
1= CreateThread(NULL,0,(LPTHREAD_START_ROUTINE) ThreadTwo,(LPVOID)NULL,0,&IDThread2); 

    
// Wait for the main thread 
    WaitForMultipleObjects(2,hThrd,TRUE,INFINITE);
    
    
return 0;
}


四 API列表:
Critical-section function Description
DeleteCriticalSection Releases all resources used by an unowned critical section object.
EnterCriticalSection Waits for ownership of the specified critical section object.
InitializeCriticalSection Initializes a critical section object.
InitializeCriticalSectionAndSpinCount Initializes a critical section object and sets the spin count for the critical section.
InitializeCriticalSectionEx Initializes a critical section object with a spin count and optional flags.
LeaveCriticalSection Releases ownership of the specified critical section object.
SetCriticalSectionSpinCount Sets the spin count for the specified critical section.
TryEnterCriticalSection Attempts to enter a critical section without blocking.

posted on 2007-07-25 18:04 夢在天涯 閱讀(6124) 評論(0)  編輯 收藏 引用 所屬分類: CPlusPlus

公告

EMail:itech001#126.com

導航

統計

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

常用鏈接

隨筆分類

隨筆檔案

收藏夾

Blogs

c#(csharp)

C++(cpp)

Enlish

Forums(bbs)

My self

Often go

Useful Webs

Xml/Uml/html

搜索

  •  

積分與排名

  • 積分 - 1819356
  • 排名 - 5

最新評論

閱讀排行榜

青青草原综合久久大伊人导航_色综合久久天天综合_日日噜噜夜夜狠狠久久丁香五月_热久久这里只有精品
  • <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>
              夜夜精品视频| 亚洲欧美日韩直播| 欧美大色视频| 亚洲免费电影在线| 欧美亚洲视频一区二区| 国内精品美女av在线播放| 老色鬼久久亚洲一区二区| 亚洲三级色网| 午夜精品网站| 激情视频一区| 欧美日韩成人免费| 欧美一级网站| 亚洲激情第一区| 亚洲欧美日韩在线| 激情成人综合| 欧美日韩国产一区| 欧美一区在线看| 亚洲激情av| 久久精品国产第一区二区三区最新章节| 一区二区三区蜜桃网| 亚洲欧美日韩精品久久亚洲区| 午夜精品福利在线| 欧美粗暴jizz性欧美20| 一本久久a久久免费精品不卡| 久久婷婷国产综合精品青草| 亚洲国产另类 国产精品国产免费| 国产一区二区三区最好精华液| 一本久久精品一区二区| 久久久.com| 亚洲网友自拍| 亚洲国产日韩欧美在线99| 国产精品久久97| 欧美aaaaaaaa牛牛影院| 国内精品久久久久久久影视蜜臀| 久久精品二区三区| 亚洲激情网站| 国产一区二区三区自拍| 国产精品第一区| 免费在线观看日韩欧美| 性色一区二区三区| 一区二区三区国产在线观看| 男女激情久久| 久久色在线播放| 欧美亚洲一级片| 亚洲网址在线| 日韩午夜高潮| 亚洲高清自拍| 国产欧美日韩亚州综合| 欧美日韩影院| 欧美人与性动交α欧美精品济南到| 亚洲另类自拍| 欧美激情一区二区三区成人| 久久久久久久久久久久久久一区 | 欧美色另类天堂2015| 久久久久久久综合色一本| 亚洲视频网在线直播| 亚洲精品视频在线播放| 六月婷婷久久| 久久精品72免费观看| 性8sex亚洲区入口| 午夜精品久久久久久久男人的天堂| 国产亚洲精品综合一区91| 国产精品电影网站| 国产精品xvideos88| 欧美日韩中字| 欧美亚男人的天堂| 国产精品久久久久aaaa樱花| 欧美精品日韩综合在线| 欧美精品乱人伦久久久久久| 欧美国产三区| 欧美日韩国产小视频| 欧美精品福利在线| 欧美另类专区| 欧美性生交xxxxx久久久| 欧美性猛交xxxx免费看久久久 | 翔田千里一区二区| 亚洲欧美在线视频观看| 午夜久久一区| 久久精品国产96久久久香蕉| 久久精品亚洲一区二区| 久久久久久欧美| 蜜桃av久久久亚洲精品| 欧美国产激情| 亚洲毛片视频| 亚洲一区二区精品在线观看| 亚洲欧美国内爽妇网| 久久黄色网页| 美日韩精品免费| 欧美日韩精品福利| 国产精品一区二区a| 国产视频一区欧美| 亚洲高清视频中文字幕| 日韩亚洲欧美一区二区三区| 亚洲色图在线视频| 欧美在线观看一二区| 久久综合五月| 亚洲日韩中文字幕在线播放| 亚洲精品偷拍| 午夜久久久久久| 免费日韩精品中文字幕视频在线| 先锋影音久久| 欧美成年视频| 国产精品色午夜在线观看| 极品少妇一区二区三区| 亚洲国产成人91精品| 一本一本久久| 久久全球大尺度高清视频| 亚洲电影在线免费观看| 亚洲一二三四区| 久久一区亚洲| 国产精品免费一区二区三区在线观看 | 久久综合久久久| 欧美精品在线极品| 国产一区自拍视频| 亚洲欧洲精品一区二区三区不卡 | 亚洲国产精品久久久久婷婷老年 | 欧美福利一区| 日韩一二三在线视频播| 久久www免费人成看片高清| 欧美日本精品一区二区三区| 国产日韩精品一区二区浪潮av| 国产精品高潮呻吟视频| 在线免费观看视频一区| 亚洲欧美日韩国产另类专区| 久久夜色精品| 正在播放欧美视频| 欧美风情在线观看| 国产一区二区中文| 亚洲一区二区精品视频| 欧美成人日本| 久久狠狠婷婷| 国产精品一二三| 亚洲网站在线| 亚洲国产精品99久久久久久久久| 欧美国产欧美亚洲国产日韩mv天天看完整| 欧美一激情一区二区三区| 正在播放亚洲| 欧美黑人多人双交| 羞羞色国产精品| 国产精品99免视看9| 亚洲精一区二区三区| 久久久天天操| 欧美夜福利tv在线| 国产精品一区一区三区| 亚洲视频在线看| 亚洲裸体视频| 欧美精品系列| 亚洲久久一区| 亚洲日本欧美天堂| 欧美a级一区二区| 亚洲人成网站色ww在线| 欧美阿v一级看视频| 久久精品久久99精品久久| 国产一区二区三区无遮挡| 欧美有码视频| 午夜亚洲一区| 国产一区视频在线观看免费| 久久激情综合网| 久久国产精品一区二区| 黄色成人在线观看| 久久综合影音| 美女爽到呻吟久久久久| 亚洲国产天堂久久国产91| 亚洲第一网站免费视频| 麻豆av一区二区三区| 91久久精品久久国产性色也91| 亚洲女性喷水在线观看一区| 日韩写真视频在线观看| 国产精品v片在线观看不卡| 亚洲欧美日韩在线不卡| 亚洲男同1069视频| 国产一级久久| 狂野欧美激情性xxxx| 久久综合给合久久狠狠狠97色69| 国产精品久久久亚洲一区 | 亚洲成人自拍视频| 暖暖成人免费视频| 亚洲毛片一区| 亚洲视频网在线直播| 国产伦精品免费视频| 久久久噜噜噜久久狠狠50岁| 久久国产精品久久w女人spa| 亚洲成人在线观看视频| 亚洲欧洲精品成人久久奇米网| 久久精品人人做人人综合| 亚洲国产精品一区二区尤物区| 性色一区二区三区| 久久精品人人| 一区二区精品| 亚洲网站啪啪| 伊人久久久大香线蕉综合直播| 性色av一区二区三区| 久久久久国内| 亚洲视频在线观看视频| 欧美一区二区三区免费观看视频| 欧美性开放视频| 美玉足脚交一区二区三区图片| 午夜精品免费视频| 亚洲成人在线观看视频| 99视频精品在线|