请考虑使用pthread的基本多线程程序。 我们有一个主线程,创建另一个线程来完成一些工作。虚假唤醒后的互斥状态
bool done = false;
mutex m;
condition c;
void foo() {
pthread_mutex_lock(&m);
//while(!done) {
pthread_cond_wait(&c, &m);
// Spuriously wakeup while child is doing work.
// child thread has NOT unlocked the mutex yet
// Do I now own the mutex?
// or am I waiting for child to unlock it?
//}
pthread_mutex_unlock(&m);
}
void * child(void *arg) {
pthread_mutex_lock(&m);
some_intense_work(); // this work is done while mutex is held!
// the main thread spuriously wakes up
// while this work is being done
// (while this child thread is holding the mutex)
done = true;
pthread_cond_broadcast(&c);
pthread_mutex_unlock(&m);
}
int main(int argc, char *argv[]) {
pthread_t p;
pthread_create(&p, NULL, child, NULL);
foo();
}
假装我们实现了一个没有周围while-clause检查谓词的等待,即使我们知道没有人应该这样做。
现在,如果在子线程正在工作时,主线程中发生虚假唤醒,那么互斥量m的状态是什么?主线程是否拥有它,而不是先让孩子解锁它,这样既拥有它呢?
或者一个虚假的唤醒只跳过等待条件,但不等待互斥锁被释放?
当['pthread_cond_wait()'](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_wait.html)成功返回时,当前线程锁定了互斥锁,而不管唤醒是否为虚假或不。如果不满意的话,负责人会在唤醒线程中仔细检查条件,再等待。 –
所以我们可以在技术上考虑这两个线程在那一刻拥有互斥量? – JMC
否;只有一个线程锁定了互斥锁 - 您不能同时锁定互斥锁,因为它不会是互斥锁。广播不会改变互斥体的互斥属性。 –