How to use CriticalSection - MFC?
I'm working on a small example and I'm a little curious using the critical section in my example. What I do is I have a CStringArray (which has 10 items added). I want to copy these 10 items (string) to another CStringArray (I do this to understand threads and critical section), I created 2 threads, Thread1 will copy the first 5 item to another CStringArray, and Thread2 will copy the rest. There are two CStringArray used here.I know only one thread can access it at a time. I wanted to know how this can be solved using the critical section or any other method.
void CThreadingEx4Dlg::OnBnClickedOk()
{
// TODO: Add your control notification handler code here
thread1 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction1,this);
thread2 = AfxBeginThread((AFX_THREADPROC)MyThreadFunction2,this);
}
UINT MyThreadFunction1(LPARAM lparam)
{
CThreadingEx4Dlg* pthis = (CThreadingEx4Dlg*)lparam;
pthis->MyFunction(0,5);
return 0;
}
UINT MyThreadFunction2(LPARAM lparam)
{
CThreadingEx4Dlg* pthis = (CThreadingEx4Dlg*)lparam;
pthis->MyFunction(6,10);
return 0;
}
void CThreadingEx4Dlg::MyFunction(int minCount,int maxCount)
{
for(int i=minCount;i<=maxCount;i++)
{
CString temp;
temp = myArray.GetAt(i);
myShiftArray.Add(temp);
}
}
a source to share
Way of using CriticalSection:
-
Declare a member variable in the class
CThreadingEx4Dlg
:CCriticalSection m_CriticalSection;
-
Lock non-thread safe code in the lock blocking block of this CriticalSection:
void CThreadingEx4Dlg::MyFunction(int minCount,int maxCount) { m_CriticalSection.Lock(); for(int i=minCount;i<=maxCount;i++) myShiftArray.Add(myArray.GetAt(i)); m_CriticalSection.Unlock(); }
a source to share
Consider using CSingleLock so that the constructor takes care of the locking and the destructor takes care of the unlocking automatically
void CThreadingEx4Dlg::MyFunction(int minCount,int maxCount)
{
CSingleLock myLock(&m_CriticalSection, TRUE);
// do work here.
// The critical section will be unlocked when myLock goes out of scope
}
a source to share