Abstract
-
Responsible for executing specific features of a process
-
Threads within a process share the same Address Space and other per-process resources, as illustrated above. So threads within the same process can share memory without having to use any System Call (系统调用)
-
There are 3 types - User Thread, Kernel Thread & Hybrid Thread
More Performant
Threads avoid the need for expensive context switching, making them 10-100 times faster than processes.
They are also faster to create and destroy compared to processes because they do not require a System Call (系统调用) to the underlying Kernel.
Easier to program
Unlike processes, different parts of a program can communicate without using Interrupts (中断) or Inter-Process Communication, making threads easier to work with.
Lack of protection between threads
Threads within the same process can access each other’s stack, potentially leading to issues like one thread overwriting another’s data. This lack of isolation can cause the entire process to fail.
Forking
When forking a process, should all threads be copied, or just the main one?
Interrupt Handling
For handling Software Interrupt, which thread should manage it?
Thread ID
- In Linux, each thread is treated as a process, so each has its own process ID. This allows the kernel to treat threads and processes in the same way
Thread group ID
All threads in the same process share the same thread group ID (TGID), which is the PID of the main thread of the process. User-space tools like
ps
andtop
often only show the TGID by default.A TGID is handy as it allows the kernel to apply operations, such as signals, that apply to all threads of the same process.
Blocking Thread
- Also known as Synchronized Threads
- A Thread remains idle while waiting for IO Operations or Network Operations, etc.
- This is straightforward to implement and understand!
Thread Table
- Tracks the threads in a process
- Similar to the Kernel’s process table, but it specifically tracks per-thread items
- Managed by the runtime system for User Thread and by the kernel for Kernel Thread
Thread Interleaving
- The way multiple threads execute concurrently, where their operations are interleaved in an unpredictable sequence due to the scheduling decisions of the kernel or runtime system
Important
Since threads often share resources (e.g., memory, variables, or files), the order in which their instructions are executed can affect the outcome of a program.
The non-deterministic nature of thread interleaving makes bugs hard to reproduce and debug.
It can lead to problems like race conditions if not handled carefully with synchronisation techniques.
PThread
pthread_yield()