程序是一组旨在执行特定任务的指令。因此,程序是一个被动实体。
正在执行(在动作中)的程序称为进程。
因此,进程是一个活动实体。当程序运行时,它可能包含相应运行的各种线程。在单线程进程中,线程本身就是进程。而在多线程进程中,我们需要在不同的线程之间切换以执行我们的程序。
1.线程切换:
线程切换是一种在同一进程中从一个线程到另一个线程的上下文切换。线程切换非常高效且成本更低,因为它只涉及切换身份和资源,例如程序计数器、寄存器和堆栈指针。线程到线程切换的成本与进入和退出内核的成本大致相同。
2. 进程切换:
进程切换是一种上下文切换,我们将一个进程与另一个进程切换。它涉及将所有进程资源与新进程所需的资源进行切换。这意味着切换内存地址空间。这包括内存地址、页表和内核资源、处理器中的缓存。
线程上下文切换和进程上下文切换的区别:
No. | Thread Context Switch | Process Context Switch |
---|---|---|
1. | TCS occurs when the CPU saves the current state of the thread and switches to another thread of the same process. | PCS occurs when the operating system’s scheduler saves the current state of the running Program (including the state of PCB) and switches to another program. |
2. | TCS helps the CPU to handle multiple threads simultaneously. | PCS involves loading of the states of the new program for it’s execution. |
3. | TCS does not involves switching of memory address spaces.All the memory addresses that the processor accounts remain saved. | PCS involves switching of memory address spaces.All the memory addresses that the processor accounts gets flushed. |
4. | Processor’s cache and Translational Lookaside Buffer preserves their state. | Processor’s cache and TLB gets flushed. |
5. | Though TCS involves switching of registers and stack pointers, it does not afford the cost of changing the address space.Hence it is more efficient. | PCS involves the heavy cost of changing the address space.Hence it is less efficient. |
6. | TCS is a bit faster and cheaper. | PCS is relatively slower and costlier. |