Creating and closing threads programmatically

Threads are ideal for performing tasks in the background while processing user input in the background. For example a Word processor does its spell checking uses a thread and can continue to process messages and allow the user to continue to work while the spell checker runs. MFC encapsulates threads of execution in the CWinThread class. Asfar as Windows is concerned, all threads are alike. MFC, however, distinguishes between two types of threads: User Interface Threads and Worker Threads. The UI threads have message loops and worker threads dont. UI thread can create windows and process messages sent to those windows. Worker threads perform background tasks that receive no direct input from the user. For example when you open a folder in operating system shell, the shll launches a UI thread that creates a window showing the folder's contents. If you drag-copy a group of files to the newly open folder, that folder's thread performs the files transfer. A classic example of a worker thread is the thread that an animation control uses to play AVI clips.
This article is an exmple of a worker thread which shows how to create and stop threads programatically. A menu displays two top level menus Start and Stop. When clicked on start two threads paint1 and paint2 are started. The Stop menu has two menu items paint1 and paint2. If user clicks on paint1 the thread stops. This is done by calling ::TerminateThread( ) function. paint1 and paint2 are thread functions. A thread function is a callback function so it must be either a static function or global function. The prototype of a thread function is as follows:
UINT threadfunc ( LPVOID param ) ;
param is a 32-bit value whose value equals the param passed to AfxBeginThread( ).

No comments: