Windows API一日一練(46)EnterCriticalSection和LeaveCriticalSection函數

來源:互聯網
上載者:User
多個線程操作相同的資料時,一般是需要按順序訪問的,否則會引導資料錯亂,無法控制資料,變成隨機變數。為解決這個問題,就需要引入互斥變數,讓每個線程都按順序地訪問變數。這樣就需要使用EnterCriticalSection和LeaveCriticalSection函數。 函數EnterCriticalSection和LeaveCriticalSection聲明如下: WINBASEAPIVOIDWINAPIEnterCriticalSection(    __inout LPCRITICAL_SECTION lpCriticalSection    );    WINBASEAPIVOIDWINAPILeaveCriticalSection(    __inout LPCRITICAL_SECTION lpCriticalSection    ); lpCriticalSection是建立臨界區對象。 調用函數的例子如下:#001 CCaiWinMsg::CCaiWinMsg(void)#002 {#003   m_hBtn = NULL;#004   m_nCount = 0;#005 #006   m_pThreadA = NULL;#007   m_pThreadB = NULL;#008 #009  //#010  InitializeCriticalSection(&m_csCount);#011 #012 }#013 #014 CCaiWinMsg::~CCaiWinMsg(void)#015 {#016  DeleteCriticalSection(&m_csCount);#017 }#018  第10行是建立臨界區對象。第16行是刪除臨界區對象。 #001 //#002 //視窗的訊息處理類。#003 //蔡軍生 2007/08/13#004 //#005 class CCaiWinMsg :#006  public CCaiWin#007 {#008 public:#009  CCaiWinMsg(void);#010  virtual ~CCaiWinMsg(void);#011 #012  //線程操作函數。#013  int AddCount(void)#014  {#015         //#016         EnterCriticalSection(&m_csCount);#017         int nRet = m_nCount++;#018         LeaveCriticalSection(&m_csCount);#019 #020         return nRet;#021  } 在函數AddCount裡調用EnterCriticalSection和LeaveCriticalSection來互斥訪問變數m_nCount。通過上面這種方法,就可以實現多線程按順序地訪問相同的變數。
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.