我们在学习线程的时候就知道,由于线程的特性是多线程共享数据,如果同时访问数据就会造成数据竞争,所以想要解决这个问题我们就需要使用线程同步(协同步调)。
解决数据竞争问题,我们可以给这片数据空间上互斥锁,这样当某一个线程使用时,其余线程就不会影响数据的使用。通常互斥量(mutex)与条件变量结合使用,用于实现线程间的安全数据共享和通信。使用条件变量可以安全地实现线程的等待和唤醒操作,而不需要依赖忙等待或其他非标准的同步机制。它与互斥量结合使用可以确保在等待和唤醒过程中的线程安全性。但是学到这就出现了“虚假唤醒”,究竟什么是虚假唤醒呢?
什么是虚假唤醒
虚假唤醒(spurious wakeup)是指在多线程编程中,一个线程在等待某个条件变量时被意外地唤醒,而实际上并没有满足唤醒条件的情况。
这里有一个简单的示例:定义一个变量a,线程1、线程3执行当a为0时对a+1,线程2、线程4执行当a为1时对a-1,循环10次,a的结果应该是0和1交替。
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<pthread.h>
#include<fcntl.h>
#include<pthread.h>
int a = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void* thread1(void* arg) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
// 这里如果使用if判断,更多线程会有虚假唤醒
if (a != 0) {
pthread_cond_wait(&cond, &mutex);// 释放锁并等待,抢到锁重新加锁
}
printf("a = %d\n", ++a);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
void* thread2(void* arg) {
for (int i = 0; i < 10; i++) {
pthread_mutex_lock(&mutex);
if (a != 1) {
pthread_cond_wait(&cond, &mutex);
}
printf("a = %d\n", --a);
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(int argc, char*argv[]) {
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
pthread_t tid1;
pthread_t tid2;
pthread_t tid3;
pthread_t tid4;
pthread_create(&tid1, NULL, thread1, NULL);
pthread_create(&tid2, NULL, thread2, NULL);
pthread_create(&tid3, NULL, thread1, NULL);
pthread_create(&tid4, NULL, thread2, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_join(tid3, NULL);
pthread_join(tid4, NULL);
return 0;
}
我们希望的结果应该是:
a = 0
a = 1
a = 0
a = 1
a = 0
a = 1
a = 0
a = 1
a = 0
a = 1
...
但是实际上会出现异常且程序会卡死:
a = 0
a = 1
a = 0
a = 1
a = 0
a = 1
a = 2
a = 3
a = 4
a = 3
a = 4
a = 5
可以看到程序并没有实现同步的需求。实际上出现的结果可能远不止如此,那为什么会出现这种情况呢?
因为当线程执行时如果条件不满足,线程调用 pthread_cond_wait
在条件变量上等待,它会释放锁直到重新抢到锁。由于条件的判断是if语句只会判断一次,在重新唤醒线程后不会再次对条件进行判断,直接向下执行,此时的条件a并不一定满足要求,所以程序出错。
那应该如何解决虚假唤醒呢?
防止虚假唤醒:我们可以将条件判断的if换成while,这样线程就会被重复判断而不再会跳出判断代码块,从而不会产生虚假唤醒这种情况了。通过循环检查条件,确保线程在被唤醒后再次验证条件是否满足,从而防止虚假唤醒带来的问题。