C语言多线程编程指南
在 C 语言中实现多线程通常需要依赖操作系统提供的 API 或第三方库。最常用的方式是使用 POSIX Threads (pthread) 库(适用于 Linux/Unix 系统)或 Windows 的线程 API。以下是多线程编程的核心概念和一个示例:
一、核心概念
- 线程创建与销毁
O pthread_create():创建线程
O pthread_join():等待线程结束
O pthread_exit():终止当前线程
- 线程同步
O 互斥锁 (Mutex):pthread_mutex_t,防止多个线程同时访问共享资源。
O 条件变量 (Condition Variables):pthread_cond_t,用于线程间的条件等待和通知。
O 信号量 (Semaphores):控制对共享资源的访问数量。
- 线程安全
O 避免竞态条件(Race Conditions),确保共享数据的一致性。
二、示例代码:使用 pthread 实现多线程
#include <stdio.h>
#include <pthread.h>
#define NUM_THREADS 5
// 共享资源
int counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 线程函数:增加计数器
void* increment_counter(void* arg) {
for (int i = 0; i < 10000; i++) {
pthread_mutex_lock(&mutex); // 加锁
counter++;
pthread_mutex_unlock(&mutex); // 解锁
}
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
// 创建线程
for (int i = 0; i < NUM_THREADS; i++) {
if (pthread_create(&threads[i], NULL, increment_counter, NULL) != 0) {
perror("Failed to create thread");
return 1;
}
}
// 等待所有线程结束
for (int i = 0; i < NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&mutex); // 销毁互斥锁
printf("Final counter value: %d\n", counter); // 预期输出 50000
return 0;
}
三、关键步骤解释
- 创建线程:pthread_create 启动新线程,执行指定函数。
- 互斥锁:通过 pthread_mutex_lock 和 pthread_mutex_unlock 保护 counter 的原子性操作。
- 等待线程结束:pthread_join 确保主线程等待所有子线程完成。
四、常见问题与解决方案
- 竞态条件:未加锁时多个线程同时修改共享数据,导致结果不可预测。使用互斥锁。
- 死锁:多个线程互相等待对方释放资源。确保锁的顺序一致。
- 资源泄漏:忘记销毁锁或未正确释放资源。使用 pthread_mutex_destroy。
五、跨平台方案
- Windows 线程:使用 CreateThread 和 WaitForMultipleObjects。
- C11 标准线程:C11 引入了 <threads.h>,但支持有限(需编译器支持,如 GCC 需开启 -std=c11)。
六、学习资源
- 书籍:《Unix 环境高级编程》(APUE)中关于线程的章节。
- 工具:Valgrind(检测内存和线程错误)、GDB(调试多线程程序)。
如果需要更深入的示例(如条件变量、信号量),或针对特定场景的解决方案,可以进一步探讨!