- Published on
KembaraXtra-Computer Science -Threads
1. Introduction to Threads
1. Introduction to Threads
- Default Program Execution: Programs typically execute instructions sequentially, handling one task at a time.
- Need for Parallelism: Threads enable programs to perform multiple tasks concurrently (in parallel). Example: A program performing a long calculation while simultaneously updating the user interface (e.g., a progress bar).
- Definition of a Thread: A thread is a schedulable unit of execution within a process, allowing for parallel execution of tasks. It can execute any program code loaded within that process.
- Task Focus: The code run by a thread typically encompasses a specific task the program aims to accomplish.
- Shared Resources: Threads within a process share the same address space, code, and other resources.
- Thread Creation: A process starts with one thread and can create additional threads as needed for parallel task handling.
- Thread ID (TID): Each thread has a unique identifier.
- Windows: Threads and processes are distinct object types. A process acts as a container for threads.
- Linux: Both processes and threads are represented using a single data type. A group of threads sharing an address space and a common process identifier is considered a process. There is no separate process type.
- User Mode: Processes have a Process ID (PID), and threads have a Thread ID (TID).
- Kernel Mode: The Linux kernel refers to a thread's ID as a PID and a process's ID as a thread group identifier (TGID).
- The Illusion of Parallelism: Although threads are said to run in parallel, the actual simultaneous execution depends on the number of processor cores.
- Processor Cores: Each processor core can execute only one thread at a time. The number of cores determines how many threads can run concurrently.
- Physical Core: A hardware implementation of a core within a CPU.
- Logical Core: The ability of a single physical core to run multiple threads simultaneously (one thread per logical core). Intel's hyper-threading is an example. Logical cores do not achieve the full parallelism of physical cores.
- Scheduling: The operating system uses a scheduler, a software component, to manage thread execution.
- Time Allocation: The scheduler allocates short periods of time (quantum) for each thread to run before suspending it to allow other threads to execute.
- Transparency: This scheduling process is mostly hidden from the thread's code, giving the illusion of continuous parallel execution.
- Developer Perspective: Developers write multithreaded applications as if all threads are running continuously in parallel.
0 Comments