多個線程操作相同的數(shù)據(jù)時,一般是需要按順序訪問的,否則會引導(dǎo)數(shù)據(jù)錯亂,無法控制數(shù)據(jù),變成隨機變量。為解決這個問題,就需要引入互斥變量,讓每個線程都按順序地訪問變量。這樣就需要使用EnterCriticalSection和LeaveCriticalSection函數(shù)。
函數(shù)EnterCriticalSection和LeaveCriticalSection聲明如下:
WINBASEAPI
VOID
WINAPI
EnterCriticalSection(
__inout LPCRITICAL_SECTION lpCriticalSection
);
WINBASEAPI
VOID
WINAPI
LeaveCriticalSection(
__inout LPCRITICAL_SECTION lpCriticalSection
);
lpCriticalSection是創(chuàng)建臨界區(qū)對象。
調(diào)用函數(shù)的例子如下:
#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行是創(chuàng)建臨界區(qū)對象。
第16行是刪除臨界區(qū)對象。
#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 //線程操作函數(shù)。
#013 int AddCount(void)
#014 {
#015 //
#016 EnterCriticalSection(&m_csCount);
#017 int nRet = m_nCount++;
#018 LeaveCriticalSection(&m_csCount);
#019
#020 return nRet;
#021 }
在函數(shù)AddCount里調(diào)用EnterCriticalSection