Search code examples
multithreadingmfccritical-section

How to use CriticalSection - MFC?


I' am working on a small example and am a bit of curious using criticalsection in my example. What I'am doing is,I have a CStringArray(which has 10 elements added to it).I want to copy these 10 elements(string) to another CStringArray(am doing this to understand threading and Critical section),I have created 2 threads,Thread1 will copy the first 5 element to another CStringArray and Thread2 will copy the rest.Here two CStringArray are being used,I know only 1 thread can access it at a time.I wanted to know how this can be solved by using criticalsection 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);
    }
}

Solution

  • The way I'd use a CriticalSection is:

    • Declare a member variable in your CThreadingEx4Dlg class:

      CCriticalSection m_CriticalSection;
      
    • Enclose your not thread safe code in a Lock-Unlock 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();
      }