Sunday, September 14, 2008

Threads - UI and Worker threads

Lets start with the basics. We would first try to gain an understanding of native threads and then gradually move to managed threads.

A thread is the basic unit to which the operating system allocates processor time. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

The figure below shows variety of models for threads and processes.

1. MS-DOS supports a single process and single thread.



Now, there can be a slight difference between the GUI application and console applications. There were two kinds of threads

1. User-Interface Threads (GUI Threads) : Commonly used to handle user input and respond to user events.

2. Worker Threads : Commonly used to handle background tasks that the user shouldn't have to wait for to continue using your application.

But why is there a distinction between user-interface threads and worker threads ?

1. User Interface thread has its own message pump/loop to process the messages in its message queue. It can implement message maps and message handlers. Worker thread does not have its own message pump. Any thread can create a window. The thread that creates the window becomes a GUI thread, it owns the window and its associated message queue.

2. A worker thread often terminates once its work is done. On other hand a UI-Thread often remains in the memory standby (inside Run() method, which does message pumping) to do the work on receiving any message.

Multiple Threads and GDI Objects

To enhance performance, access to graphics device interface (GDI) objects (such as palettes, device contexts, regions, and the like) is not serialized. This creates a potential danger for processes that have multiple threads sharing these objects. For example, if one thread deletes a GDI object while another thread is using it, the results are unpredictable. This danger can be avoided simply by not sharing GDI objects. If sharing is unavoidable (or desirable), the application must provide its own mechanisms for synchronizing access.

In Win32 programming, CreateThread function is used to create a thread. It takes starting address of the code the new thread is to execute. If the thread is a GUI thread, it is its responsibility to provide a message loop.

In MFC, you were supposed to derive from CWinThread to create a user-interface thread.

No comments: