线程互斥与加锁机制详解
一、互斥锁基础原理
当多个线程访问共享资源时,通过互斥锁实现原子操作保护。互斥锁保证临界区代码的独占执行,其工作流程可表示为:
加锁 → 访问共享资源 → 解锁 \text{加锁} \rightarrow \text{访问共享资源} \rightarrow \text{解锁} 加锁→访问共享资源→解锁
二、核心API函数
- 锁初始化:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // 静态初始化
// 或动态初始化
pthread_mutex_init(&mutex, NULL);
- 加锁操作:
int pthread_mutex_lock(pthread_mutex_t *mutex); // 阻塞式加锁
int pthread_mutex_trylock(pthread_mutex_t *mutex); // 非阻塞加锁
- 解锁操作:
int pthread_mutex_unlock(pthread_mutex_t *mutex);
- 销毁锁:
pthread_mutex_destroy(&mutex);
三、典型应用场景
#include <pthread.h>
int counter = 0;
pthread_mutex_t mutex;
void* thread_func(void* arg) {
for(int i=0; i<100000; ++i){
pthread_mutex_lock(&mutex);
counter++; // 临界区操作
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t t1, t2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&t1, NULL, thread_func, NULL);
pthread_create(&t2, NULL, thread_func, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("Final counter: %d\n", counter); // 正确输出200000
pthread_mutex_destroy(&mutex);
return 0;
}
四、关键实践要点
-
锁粒度控制:
- 过粗:降低并发性能
- 过细:增加锁开销
- 经验公式: T c r i t i c a l < 1 3 T t o t a l T_{critical} < \frac{1}{3}T_{total} Tcritical<31Ttotal
-
错误检测机制:
if(pthread_mutex_lock(&mutex) != 0){
perror("Mutex lock failed");
// 错误处理
}
- 死锁预防策略:
- 固定加锁顺序
- 使用trylock+超时机制
- 避免嵌套加锁
五、性能优化方案
- 读写锁(pthread_rwlock_t)适用读多写少场景
- 自旋锁(pthread_spinlock_t)适用于短临界区
- 无锁编程(原子操作)示例:
__atomic_add_fetch(&counter, 1, __ATOMIC_SEQ_CST);
实验数据显示:在4核CPU环境下,合理使用互斥锁可使多线程程序达到约75%的线性加速比。建议通过valgrind --tool=helgrind
进行线程竞争检测。