Log in ....Tribune

Monday, November 4, 2002
Feature

Multithreading for multitasking
Sarabjeet Singh Kanwal

WHEN a program code executes, it is called process. A traditional (heavy weight) process has a single flow of control, i.e. one thread. It can perform only one task at a time. Modern operating systems support the concept of multithreading. In multithreading, a process is divided into two or more mini-processes, which appear to run in a parallel fashion i.e. simultaneously. Each mini-process is called a thread (light weight process). A process having multiple threads (many flows of control) can obviously perform more than one task at a time.

A thread is the basic unit of CPU utilisation whereas all threads of a process have their own thread ID, program counter, register set and stack; they share code section, data section and files with one another.

A PC has only a single processor. Therefore it can run a single thread at a time. Threads share CPU just as processes do i.e. one thread runs, then it stops (for some time) and second runs. The CPU switching is so fast that they appear running parallel.

Examples

1. A word processor has one thread for reading keystrokes from user, second thread for performing auto-save function, and other threads for doing auto-spell-check and auto-grammar-check functions in the background.

2. A Web browser has one thread to download an image, another to download text at the same time, and a third one to read keystrokes from the client. Hence, with a slow Internet connection, we are able to start filling up a form on a Web page when the browser is still downloading images on the same page.

3. A Web server may accept thousands of client requests for text, images, sound and videos simultaneously. A single-threaded process on the Web-server may serve only a single client at a time. An efficient server however, runs a multithreaded process that creates separate threads for listening to each client’s request. Solaris 2, Windows 2000 and Linux 2.2 are the operating systems that provide support for multithreading. Java is one of the few programming languages that provide support for this concept at the language level.

Benefits

If a part of an application is blocked or is performing a lengthy process (as in example 2), the other thread can still allow user to interact with the application.

1) Threads share CPU, resources and memory of a system. CPU is busy most of the times running some thread. This considerably increases the speed of execution.

2) Allocating memory and resources for new process creation is costly. Alternatively, since threads of a process use resources of the process to which they belong, it is easier to create a new thread than a new process for doing the same task.

3) On a multiprocessor system, every thread of a multithreaded process gets separate processor to run whereas a single threaded process can get benefit of only one processor, no matter how many are available.