Chapter 4. Dividing C++ Programs into Multiple Threads
In this Chapter
The work of a sequential program can be divided between routines within a program. Each routine is assigned a specific task, and the tasks are executed one after another. The second task cannot start until the first task finishes, the third task cannot start until the second task finishes, and so on. This scheme works fine until performance and complexity boundaries are encountered . In some cases, the only solution to a performance problem is to allow the program to do more than one task simultaneously . In other situations the work that routines within a program have to do is so involved that it makes sense to think of the routines as mini-programs within the main program. Each mini-program executes concurrently within the main program. Chapter 3 presented methods for breaking a single process up into multiple processes, where each process executes a separate program. This method allows an application to do more than one thing at a time. However, each process has its own address space and resources. Because each program is in a separate address space, communication between routines becomes an issue. Interprocess communication techniques such as pipes, fifos, and environment variables are needed to communicate between the separately executing parts. Sometimes it is desirable to have a single program do more than one task at a time without dividing the program into multiple programs. Threads can be used in these circumstances. Threads allow a single program to have concurrently executing parts , where each part has access to the same variables , constants, and address space. Threads can be thought of as mini-programs within a program. When a program is divided into separate processes, as we did in Chapter 3, there is a certain amount of overhead associated with executing each of the separate programs. Threads require less overhead to execute. Threads can be thought of as lightweight processes , offering many of the advantages of processes without the communication requirements that separate processes require. Threads provide a means to divide the main flow of control into multiple, concurrently executing flows of control. |