home Tech Library Tech Forum
Publisher
 
Basics of Multithreading       
 
 
Creating User-Interface Threads in MFC
 
 

 

To create a user-interface thread, first derive a class from CWinThread and implement the class using the DECLARE_DYNCREATE and IMPLEMENT_DYNCREATE in the .h and .cpp file respectively. We can override the functions in the derived class, but it should be noted that, it is mandatory to override the following functions.
    1. ExitIntstance
           This is the clean up function for the object when the thread terminates.
    2. InitInstance
          Perform the thread based initialization.
    3. OnIdle
         This is used to perform the thread specific idle time processing.
    4. PreTranslateMessage
         This can be used to filter messages before they are dispatched to TranslateMessage and
         DispatchMessage.
    5. ProcessWndProcException
         This function can be used to intercept unhandled exceptions thrown by the thread’s message
         and command handlers.
    6. Run
         This is the controlling function of the thread and it contains the message pump.

The thread creation is actually achieved using the AfxBeginThread function and MFC provide two overloaded versions of this function. One of them is used for creating user-interface threads and the other for creating worker threads.

The user-interface version of AfxBeginThread takes these parameters
     1. The RUNTIME_CLASS structure of the class we derived from CWinThread
     2. Thread Priority Level which is optional and the default are normal priority.
     3. Desired Stack size of the thread (optional). By default its the same as the creator stack size.
     4. Thread State which is optional. By default it is CREATE_SUSPENDED
     5. Security Attributes of the thread (Optional). By default it’s the same as the creator.

Example:

CWinThread* AfxBeginThread (
         CRuntimeClass* pUserThread,
         int nPriority = THREAD_PRIORITY_NORMAL,
         UINT nStackSize = 0,
         DWORD dwCreateFlags = 0,
        LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL);


The return value will be a pointer to the newly created Thread object and NULL if it fails.

To terminate a thread call the AfxEndThread from with in the thread or return from the controlling function in case of a worker thread.
   
  RELATED TOPICS  
What is a thread?
Thread Pools
Multithreading
Thread Vs Process
MultiThreading support in C++ and MFC
Creating worker Threads in MFC
Terminating Threads
Thread Synchronization
Designing a Thread-safe class
Semaphore in MFC
Mutex in MFC
Critical Section in MFC
Event Objects in MFC
CSingleLock and CMultiLock in MFC


 
           
Home | Profile | Users | Library | Publisher | Tech Forum | News | Contact Us