Threads and Thread Synchronization in MFC By Gregory Mortensen CSIS 4330 Advanced Windows Programming
User created threads in MFC Worker threads, thin wrapper around win32 API threads. UI or user interface threads have a message map. However UI threads messages are asynchronous from the GUI thread.
Worker threads in MFC Use AfxBeginThread –which calls __begintheadex –does change the parameter list order from the Win32 API CreateThread function –returns a CWinThread pointer –Doesn’t have a message map!
User Interface (UI) threads… Use AfxBeginThread –Which calls __beginthreadex –Which creates a HWND –Cast your UI class (which is inherited from CWinThread) to CRuntimeClass when calling AfxBeginThread, eg AfxBeginThread( RUNTIME_CLASS( yourUIClass ))
User Interface (UI) threads cont. As heretofore mentioned, your UI thread must inherit from CWinThread Must use the macro DECLARE_DYNCREATE in the class declaration Must use the macro IMPLEMENT_DYNCREATE in the class definition WM_QUIT means terminate the thread
Synchronization CCriticalSection CEvent CMutex CSemaphore
Lock Method Lock for Kernal API Objects equates to WaitForSingleObject Lock for CCriticalSection equates to EnterCriticalSection
Unlock CCriticalSection unlock equates to LeaveCriticalSection CMutex unlock equates to ReleaseMutex CSemaphore unlock equates to ReleaseSemaphore, and just as in the API you can release more than one resource at a time CEvent has no Unlock! –Use Set, Reset, or Pulse instead
Multilock Class Same as WaitForMultipleObject You pass in the Multilock class the array of kernel objects and tell it how many there are You can select to wait for all, or wait for one kernel object Eg: –CEvent g_event[4]; –CMultiLock g_mLock(g_event,4); –g_mLock(INFINITE, false);