进程与线程管理原理
进程与线程管理原理
1. 技术分析
1.1 进程概念
进程是程序的执行实例:
进程特性 独立性: 独立的地址空间 并发性: 多个进程同时执行 动态性: 生命周期变化 进程状态: 就绪: 等待CPU 运行: 执行中 阻塞: 等待I/O 终止: 执行完成1.2 线程概念
线程是进程内的执行单元:
线程特点 共享资源: 共享进程地址空间 轻量级: 创建开销小 并发执行: 同一进程内多个线程 线程类型: 用户线程: 用户态管理 内核线程: 内核管理 混合线程: 用户+内核1.3 进程vs线程
| 特性 | 进程 | 线程 |
|---|---|---|
| 地址空间 | 独立 | 共享 |
| 资源开销 | 大 | 小 |
| 通信方式 | IPC | 共享内存 |
| 并发粒度 | 粗 | 细 |
2. 核心功能实现
2.1 进程创建
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main() { printf("父进程 PID: %d\n", getpid()); // 创建子进程 pid_t pid = fork(); if (pid < 0) { perror("fork failed"); exit(1); } else if (pid == 0) { // 子进程 printf("子进程 PID: %d, 父进程 PPID: %d\n", getpid(), getppid()); // 执行新程序 execl("/bin/echo", "echo", "Hello from child process", NULL); perror("execl failed"); exit(1); } else { // 父进程 printf("创建子进程 PID: %d\n", pid); // 等待子进程结束 int status; waitpid(pid, &status, 0); if (WIFEXITED(status)) { printf("子进程正常结束,退出码: %d\n", WEXITSTATUS(status)); } else if (WIFSIGNALED(status)) { printf("子进程被信号终止,信号: %d\n", WTERMSIG(status)); } } return 0; }2.2 线程创建与同步
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 5 int counter = 0; pthread_mutex_t mutex; void *worker(void *arg) { int id = *(int *)arg; for (int i = 0; i < 1000; i++) { pthread_mutex_lock(&mutex); counter++; pthread_mutex_unlock(&mutex); } printf("线程 %d 完成,counter = %d\n", id, counter); pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; int thread_ids[NUM_THREADS]; pthread_mutex_init(&mutex, NULL); // 创建线程 for (int i = 0; i < NUM_THREADS; i++) { thread_ids[i] = i; int rc = pthread_create(&threads[i], NULL, worker, &thread_ids[i]); if (rc != 0) { printf("线程创建失败: %d\n", rc); exit(1); } } // 等待所有线程完成 for (int i = 0; i < NUM_THREADS; i++) { pthread_join(threads[i], NULL); } printf("最终 counter = %d\n", counter); pthread_mutex_destroy(&mutex); return 0; }2.3 线程池实现
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <queue> using namespace std; typedef struct { void (*func)(void *); void *arg; } Task; class ThreadPool { private: pthread_t *threads; queue<Task> tasks; pthread_mutex_t mutex; pthread_cond_t cond; int num_threads; bool shutdown; static void *thread_func(void *arg) { ThreadPool *pool = (ThreadPool *)arg; pool->worker(); return NULL; } void worker() { while (!shutdown) { pthread_mutex_lock(&mutex); while (tasks.empty() && !shutdown) { pthread_cond_wait(&cond, &mutex); } if (shutdown) { pthread_mutex_unlock(&mutex); return; } Task task = tasks.front(); tasks.pop(); pthread_mutex_unlock(&mutex); task.func(task.arg); } } public: ThreadPool(int n) : num_threads(n), shutdown(false) { pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); threads = new pthread_t[num_threads]; for (int i = 0; i < num_threads; i++) { pthread_create(&threads[i], NULL, thread_func, this); } } ~ThreadPool() { shutdown = true; pthread_cond_broadcast(&cond); for (int i = 0; i < num_threads; i++) { pthread_join(threads[i], NULL); } pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); delete[] threads; } void add_task(void (*func)(void *), void *arg) { pthread_mutex_lock(&mutex); tasks.push({func, arg}); pthread_mutex_unlock(&mutex); pthread_cond_signal(&cond); } };3. 性能对比
3.1 进程vs线程开销
| 操作 | 进程 | 线程 |
|---|---|---|
| 创建时间 | 约1ms | 约0.1ms |
| 内存开销 | 约1MB | 约1KB |
| 切换时间 | 约10us | 约1us |
3.2 同步机制对比
| 机制 | 开销 | 适用场景 |
|---|---|---|
| 互斥锁 | 低 | 临界区保护 |
| 读写锁 | 中 | 读多写少 |
| 条件变量 | 低 | 线程间通信 |
| 信号量 | 低 | 资源计数 |
3.3 调度算法对比
| 算法 | 特点 | 适用场景 |
|---|---|---|
| FIFO | 简单 | 实时系统 |
| RR | 公平 | 分时系统 |
| SJF | 短作业优先 | 批处理 |
| MLFQ | 多级反馈 | 通用系统 |
4. 最佳实践
4.1 线程安全
// 使用互斥锁保护共享资源 pthread_mutex_t mutex; void increment_counter() { pthread_mutex_lock(&mutex); counter++; pthread_mutex_unlock(&mutex); } // 使用RAII封装锁 class LockGuard { private: pthread_mutex_t &mutex; public: LockGuard(pthread_mutex_t &m) : mutex(m) { pthread_mutex_lock(&mutex); } ~LockGuard() { pthread_mutex_unlock(&mutex); } };4.2 避免死锁
// 按顺序获取锁 void safe_operation() { pthread_mutex_lock(&mutex1); pthread_mutex_lock(&mutex2); // 操作... pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); } // 使用trylock bool try_operation() { if (pthread_mutex_trylock(&mutex1) != 0) { return false; } if (pthread_mutex_trylock(&mutex2) != 0) { pthread_mutex_unlock(&mutex1); return false; } // 操作... pthread_mutex_unlock(&mutex2); pthread_mutex_unlock(&mutex1); return true; }5. 总结
进程与线程是操作系统并发的核心:
- 进程:资源分配的基本单位
- 线程:CPU调度的基本单位
- 同步机制:保证数据一致性
- 线程池:提高并发效率
对比数据如下:
- 线程创建开销是进程的1/10
- 互斥锁开销最低
- MLFQ是Linux默认调度算法
- 推荐使用线程池管理大量并发任务
