前置知识—进程和线程
进程(任务)
what ?
In computing, a process is the instance of a computer program that is being executed. It contains the program code and its activity. Depending on the operating system (OS), a process may be made up of multiple threads of execution that execute instructions concurrently
- 是被执行的程序
- 进程中有源代码和进程的活跃度
- 根据不同的操作系统,一个进程或许由多个线程组成,多线程是为了并发的执行命。
一个进程由什么组成?
- An image (与程序相关联的可执行机器代码)
- 内存
- Operating system descriptors分配的资源
- 安全属性
- CPU的上下文
因为安全性和可靠性,现代操作系统不允许进程之间直接通讯,采用了一种严格的通讯方法叫做 IPC (Inter-process communication)。
多任务的操作系统存在多个进程同时执行,单核CPU一次性只能执行一个进程,CPU进行切换任务,不必等待上一个任务执行结束。
通常,程序中的主程序只有单个进程和多个子进程。
线程
What ?
In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.[1] The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently and sharing resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its executable code and the values of its dynamically allocated variables and non-thread-local global variablesat any given time.
- 线程是最小的一系列程序指令。
- 线程是进程中的一个部分。
- 多线程可以存在一个进程中,并发执行和共享资源。
进程 vs 线程
- 进程之间是独立的,而线程是进程的子集
- 进程中状态信息比线程多,然而一个进程中的多线程共享着和进程一样的状态信息
- 进程有独立的地址空间,线程只是分享进行的地址空间
- 进程通讯依据系统提供的IPC方法
- 上下文切换而言,线程切换比进程快