进程、线程与协程 | Processes, Threads, and Coroutines

进程 | Processes

定义 | Definition

进程是操作系统中运行的一个独立的程序实例,具有自己的内存空间和系统资源。

A process is an independent program instance running in an operating system, with its own memory space and system resources.

特点 | Characteristics

  • 独立性 | Independence:每个进程独立运行,互不干扰。 Each process runs independently, without interfering with others.
  • 资源分配 | Resource Allocation:进程拥有独立的资源,如内存、文件句柄等。 Processes have their own resources, such as memory and file handles.
  • 上下文切换 | Context Switching:进程切换开销大,需要保存和恢复 CPU 上下文。 Context switching between processes is costly, requiring saving and restoring the CPU context.

创建和销毁 | Creation and Termination

  • 创建 | Creation:通过系统调用(如 fork)创建新进程。 Created using system calls like fork.
  • 销毁 | Termination:进程完成任务或被终止后,系统回收其资源。 Terminated when it completes its task or is killed, with the system reclaiming its resources.

示例 | Example

// Example in C
#include <stdio.h>
#include <unistd.h>
 
int main() {
    pid_t pid = fork();
    if (pid == 0) {
        // Child process
        printf("This is the child process\n");
    } else {
        // Parent process
        printf("This is the parent process\n");
    }
    return 0;
}

线程 | Threads

定义 | Definition

线程是进程内的一个执行单元,共享进程的资源,但具有独立的执行路径。

A thread is an execution unit within a process, sharing the process’s resources but having an independent execution path.

特点 | Characteristics

  • 共享资源 | Resource Sharing:线程共享进程的内存空间和资源。 Threads share the process’s memory space and resources.
  • 轻量级 | Lightweight:线程比进程更轻量级,创建和切换开销较小。 Threads are more lightweight than processes, with lower creation and switching costs.
  • 并发执行 | Concurrent Execution:同一进程内的多个线程可以并发执行。 Multiple threads within the same process can execute concurrently.

创建和销毁 | Creation and Termination

  • 创建 | Creation:通过库函数(如 pthread_create)创建新线程。 Created using library functions like pthread_create.
  • 销毁 | Termination:线程完成任务或被终止后,线程的资源被回收。 Terminated when it completes its task or is killed, with its resources being reclaimed.

示例 | Example

// Example in C using pthreads
#include <pthread.h>
#include <stdio.h>
 
void* thread_func(void* arg) {
    printf("This is a thread\n");
    return NULL;
}
 
int main() {
    pthread_t thread;
    pthread_create(&thread, NULL, thread_func, NULL);
    pthread_join(thread, NULL);
    return 0;
}

协程 | Coroutines

定义 | Definition

协程是一种比线程更轻量级的用户级任务调度方式,允许在单个线程内暂停和恢复执行。

A coroutine is a user-level task scheduling method that is more lightweight than threads, allowing pausing and resuming execution within a single thread.

特点 | Characteristics

  • 轻量级 | Lightweight:协程切换开销极小,不涉及内核态切换。 Coroutines have minimal switching overhead and do not involve kernel-mode switching.
  • 协作式多任务 | Cooperative Multitasking:协程通过显式调用让出控制权,实现多任务调度。 Coroutines use cooperative multitasking by explicitly yielding control to achieve multitasking.
  • 共享同一线程的执行上下文 | Shared Execution Context:协程在同一线程内共享执行上下文和栈空间。 Coroutines share the execution context and stack space within the same thread.

创建和销毁 | Creation and Termination

  • 创建 | Creation:通过语言级支持或库(如 Python 的 asyncio)创建协程。 Created using language-level support or libraries like Python’s asyncio.
  • 销毁 | Termination:协程完成任务后由调度器回收。 Reclaimed by the scheduler after the coroutine completes its task.

示例 | Example

# Example in Python using asyncio
import asyncio
 
async def coroutine_func():
    print("This is a coroutine")
    await asyncio.sleep(1)
    print("Coroutine done")
 
async def main():
    await coroutine_func()
 
asyncio.run(main())

比较 | Comparison

特性进程线程协程
独立性独立的内存空间和资源共享进程的内存空间和资源共享线程的执行上下文
创建开销最低
切换开销最低
并发性否(通常在单线程内协作)
适用场景多任务并行,资源隔离多任务并行,资源共享高效的任务切换和并发处理

进程适用于需要资源隔离和稳定性的场景,线程适用于需要高效并发执行的场景,而协程则适用于需要极高并发且开销极低的场景。 Processes are suitable for scenarios requiring resource isolation and stability, threads for efficient concurrent execution, and coroutines for scenarios requiring extremely high concurrency with minimal overhead.