You should consider creating new threads any time your program handles asynchronous activity. Programs with multiple windows, for example, generally benefit from creating a thread for each window. Most MDI (Multi-Document Interface) applications create threads for the child windows. A program that interacts with several asynchronous devices creates threads for responding to each device.
A desktop publisher, for example, might assign responsibility for the main window to a single thread of high priority. When the user initiates a lengthy operation, such as pouring text into an empty layout, the program creates a new thread to do the formatting in the background. Meanwhile, the first thread continues to manage the main window and responds quickly to new commands from the user. If the user then asks to cancel the formatting, the input thread can interrupt the formatting thread by terminating it. Threads can also be useful for performing slow disk operations in the background or for communicating with other processes. One thread sends messages, and another waits to receive them.
NOTE
Each window that a program creates belongs to the thread that creates it. When a thread creates a window, the system gives it a message queue, and the thread must enter a message loop to read from its queue. If a single thread creates all of a program’s windows, the program needs only a single message loop. Conversely, any thread that wants to receive messages must create a window for itself, even if the window remains hidden. Only threads that create windows get message queues.
One example of synchronous activity that is familiar to many users would be using a contemporary word processor with the automatic spell-checker enabled. Here one (or probably more) threads are responsible for responding to the keyboard activity, updating the text on the screen, and managing a regular update of the backup version of the working file. At the same time, another thread is busy checking what has been written against the selected dictionary or dictionaries and, when a word is not recognized, sending a message to tell the display thread to highlight the unknown word. As long as the word processor is working smoothly, all of these tasks are occurring synchronously even though at different rates.
Any thread can create other threads. Any thread can also create new processes. When a program needs to do several things at once, it must decide whether to create threads or processes to share the work. Choose threads whenever you can because the system creates them quickly and they interact with each other easily. Creating a process takes longer because the system must load a new executable file image from the disk. However, a new process has the advantage of receiving its own private address space. You might also choose processes over threads as a way of preventing them from interfering, even accidentally, with each other’s resources. (For more details about processes, refer to Chapter 15.)