线程是操作系统能够调度的最小执行单元。一个进程可以包含多个线程,它们共享进程的内存空间(如全局变量、堆等),但每个线程拥有自己的栈和寄存器状态。这使得线程间通信比进程间通信更高效。
准备工作:包含头文件并链接库
在 Linux 或类 Unix 系统中,我们使用 pthread.h 头文件,并在编译时链接 libpthread 库。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
// 编译命令:
// gcc -o my_thread_program thread_example.c -lpthread
创建一个简单线程
使用 pthread_create() 函数可以创建新线程。该函数需要四个参数:
pthread_t *thread:用于存储新线程 ID 的指针 const pthread_attr_t *attr:线程属性(通常设为 NULL 使用默认值) void *(*start_routine)(void *):线程执行的函数 void *arg:传递给线程函数的参数
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 线程执行函数
void* thread_function(void* arg) {
int id = *(int*)arg;
printf("子线程 %d 正在运行!\n", id);
sleep(2); // 模拟耗时操作
printf("子线程 %d 执行完毕。\n", id);
return NULL;
}
int main() {
pthread_t thread_id;
int thread_arg = 1;
// 创建线程
if (pthread_create(&thread_id, NULL, thread_function, &thread_arg) != 0) {
perror("线程创建失败");
exit(EXIT_FAILURE);
}
printf("主线程继续执行...\n");
// 等待子线程结束
pthread_join(thread_id, NULL);
printf("主线程结束。\n");
return 0;
}
线程的等待与分离
创建线程后,主线程通常需要等待子线程完成,这通过 pthread_join() 实现。如果不关心子线程结果,也可以调用 pthread_detach() 将其设为“分离状态”,系统会自动回收资源。
// 分离线程示例
pthread_t tid;
pthread_create(&tid, NULL, thread_function, NULL);
pthread_detach(tid); // 不再需要 join
线程同步:互斥锁(Mutex)
当多个线程访问共享资源(如全局变量)时,必须使用同步机制避免数据竞争。最常用的是互斥锁(mutex)。
#include <stdio.h>
#include <pthread.h>
int global_counter = 0;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* increment_counter(void* arg) {
for (int i = 0; i < 100000; i++) {
pthread_mutex_lock(&mutex);
global_counter++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_create(&t1, NULL, increment_counter, NULL);
pthread_create(&t2, NULL, increment_counter, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("最终计数器值:%d\n", global_counter); // 应为 200000
return 0;
}
常见问题与最佳实践
- 始终检查
pthread_create() 的返回值 - 避免在多个线程中直接修改共享变量而不加锁
- 使用
pthread_join() 确保主线程不会提前退出 - 资源清理:线程结束后记得释放动态分配的内存
总结
通过本教程,你已经掌握了 C语言线程创建、C语言多线程编程 的基本方法,以及如何使用 pthread线程管理 和 线程同步C语言 技术(如互斥锁)来编写安全的并发程序。多线程虽强大,但也需谨慎使用,避免死锁和竞态条件。
建议在实际项目中从小规模开始尝试,逐步深入理解线程生命周期、同步原语(如条件变量、信号量)等高级主题。