C 语言 posix 线程
外观
简介[编辑 | 编辑源代码]
POSIX线程(通常称为pthreads)是遵循POSIX标准的线程库,用于在C语言中实现多线程编程。它提供了一套API,允许开发者创建、管理和同步线程,从而充分利用多核处理器资源。pthreads是Unix/Linux系统中的标准线程实现,也是跨平台多线程开发的重要工具。
多线程编程的核心目标是实现并发执行,即多个线程在同一进程内共享内存空间,但拥有独立的执行流。与多进程相比,线程的创建和切换开销更小,但需要更谨慎地处理资源共享和同步问题。
核心概念[编辑 | 编辑源代码]
线程与进程的区别[编辑 | 编辑源代码]
- 进程:独立的执行单元,拥有独立的地址空间和系统资源。
- 线程:轻量级进程,共享同一进程的地址空间和资源,但拥有独立的栈和程序计数器。
pthreads 基本API[编辑 | 编辑源代码]
以下是pthreads的核心函数:
pthread_create()
:创建新线程。pthread_join()
:等待线程终止。pthread_exit()
:显式退出线程。pthread_mutex_lock()
:互斥锁,用于同步。
基础示例[编辑 | 编辑源代码]
创建线程[编辑 | 编辑源代码]
以下示例展示如何创建并运行一个线程:
#include <stdio.h>
#include <pthread.h>
// 线程函数
void* print_message(void* msg) {
printf("线程消息: %s\n", (char*)msg);
pthread_exit(NULL);
}
int main() {
pthread_t thread;
char* message = "Hello, pthread!";
// 创建线程
int ret = pthread_create(&thread, NULL, print_message, (void*)message);
if (ret != 0) {
perror("线程创建失败");
return 1;
}
// 等待线程结束
pthread_join(thread, NULL);
printf("主线程结束\n");
return 0;
}
输出:
线程消息: Hello, pthread! 主线程结束
线程同步(互斥锁)[编辑 | 编辑源代码]
当多个线程访问共享资源时,需使用互斥锁(Mutex)避免竞争条件:
#include <stdio.h>
#include <pthread.h>
int counter = 0;
pthread_mutex_t lock;
void* increment_counter(void* arg) {
pthread_mutex_lock(&lock);
for (int i = 0; i < 100000; i++) counter++;
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
int main() {
pthread_t t1, t2;
pthread_mutex_init(&lock, NULL);
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", counter); // 应为200000
pthread_mutex_destroy(&lock);
return 0;
}
高级主题[编辑 | 编辑源代码]
条件变量[编辑 | 编辑源代码]
条件变量(pthread_cond_t
)用于线程间通信,允许线程等待特定条件成立:
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready = 0;
void* consumer(void* arg) {
pthread_mutex_lock(&mutex);
while (!ready) pthread_cond_wait(&cond, &mutex);
printf("条件满足,继续执行\n");
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
void* producer(void* arg) {
pthread_mutex_lock(&mutex);
ready = 1;
pthread_cond_signal(&cond);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
线程属性[编辑 | 编辑源代码]
可通过pthread_attr_t
设置线程属性(如栈大小、分离状态):
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_t thread;
pthread_create(&thread, &attr, thread_function, NULL);
实际应用案例[编辑 | 编辑源代码]
多线程Web服务器[编辑 | 编辑源代码]
Web服务器(如Nginx)使用线程池处理并发请求: 1. 主线程监听端口,接收连接。 2. 工作线程处理请求(读取文件、生成响应)。
并行计算[编辑 | 编辑源代码]
将大规模计算任务(如矩阵乘法)分解为多个线程并行执行:
常见问题[编辑 | 编辑源代码]
- Q: 线程安全是什么?
A: 函数或代码在多线程环境下能正确执行,无需额外同步。
- Q: 如何避免死锁?
A: 按固定顺序获取锁,或使用超时机制(如pthread_mutex_trylock
)。
总结[编辑 | 编辑源代码]
POSIX线程是C语言多线程编程的核心工具,适用于需要高并发和资源共享的场景。初学者应重点掌握线程创建、同步机制(互斥锁、条件变量),而高级用户可探索线程池、性能优化等进阶主题。