Intuitively, a thread is a stream of instructions from a program being executed by a processor.
In a traditional single-threaded system each process has a context and a single thread of execution:
Single-Threaded Model
In a multi-threaded system a process can spawn multiple child threads. Each thread has its own stack and registers but shares the code, files, and data of the parent process:
Multi-Threaded Model
A master thread listens for requests. When a request is received, the master creates a slave thread to service the request, then resumes listening for more requests:
while(true) {
request = listen(); // blocks if
request queue is empty
slave = new SlaveThread(request);
slave.start();
}
In an interactive program the master thread is the user interface. Requests come in the form of user inputs such as button clicks or menu selections. While slaves are servicing earlier requests such as spell checking, compiling, downloading, etc, the user may continue to use the program.
In a server the master listens for requests from clients. Slaves are spawned to service client requests. For example, in an on-line Tic-Tac-Toe game, a client plays Tic-Tac-Toe with a slave while the master listens for new clients.
The child threads of a process all have access to the data, files, and other resources owned by the parent. While this can create synchronization problems, it enables efficient memory sharing communication between threads.
Context switching between the child threads of a process is fast. Only the stack and registers need to be swapped. Context switching between processes can be 30 times slower. Each process has its own page table. Many pages may have been swapped out of main memory.
Some multi-threading systems can exploit multiprocessor architectures by assigning each thread to a different processor.
Multi-threading-- creating, scheduling, and managing threads-- can be implemented by the operating system (kernel threads), by the application (user threads), or by both.
Many-to-one model
One-to-one model
One-to-many model
Many-to-many model
POSIX Pthreads, Mach C-threads, and Solaris 2 UI-threads are user thread libraries.
Windows (NT, 2000, XP) and most modern operating systems provide kernel threads.
Java threads are supported by the Java VM and don't really fall into either category.