【发布时间】:2014-04-25 08:00:17
【问题描述】:
我正在尝试使用互斥体而不是信号量,因为我想要信号量行为但二进制(不计数)。 (也许你会注意到我正处于尝试模拟 Sleeping Barber 算法的早期阶段。)这是我的代码:
#include <stdio.h>
#include <pthread.h>
int main( int argc, char** argv ) {
int freeSeats = 6;
pthread_mutexattr_t mutexAttr;
pthread_mutex_t custWaiting, wrAccess, barberReady;
pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_SHARED);
pthread_mutex_init(&custWaiting, &mutexAttr);
pthread_mutex_init(&wrAccess, &mutexAttr);
pthread_mutex_init(&barberReady, &mutexAttr);
pthread_mutex_lock(&custWaiting);
pthread_mutex_lock(&custWaiting);
pthread_mutex_lock(&custWaiting);
fprintf(stdout, "got here\n\n");
return 0;
}
当我第一次执行时,它会按预期运行(线程被阻塞,命令行挂起,而我的程序等待能够锁定)。当我杀死该程序并再次运行它时,它会打印“到这里”,这是不应该的。为什么这只会在第二次(以及所有后续)尝试时失败,而在第一次尝试时不会失败?
令人费解的是,如果我将代码修改如下(仅 init 和 lock 行):
#include <stdio.h>
#include <pthread.h>
int main( int argc, char** argv ) {
int freeSeats = 6;
pthread_mutexattr_t mutexAttr;
pthread_mutex_t custWaiting, wrAccess, barberReady;
pthread_mutexattr_setpshared(&mutexAttr, PTHREAD_PROCESS_SHARED);
int y = pthread_mutex_init(&custWaiting, &mutexAttr);
y = pthread_mutex_init(&wrAccess, &mutexAttr);
y = pthread_mutex_init(&barberReady, &mutexAttr);
int x = pthread_mutex_lock(&custWaiting);
x = pthread_mutex_lock(&custWaiting);
x = pthread_mutex_lock(&custWaiting);
fprintf(stdout, "got here\n\n");
return 0;
}
...然后它每次都有效。之所以如此令人抓狂,是因为我无法检查 pthread_mutex_whatever() 上的错误代码,因为当我尝试捕获错误代码时它不会失败。如果我不打算使用它们,我不想将返回值分配给ints。如您所见,我根本没有使用x 或y;只需将 init 和 lock 函数的返回值分配给它们。那么为什么这会如此剧烈地改变互斥体的行为呢?还是我错过了其他东西?我做错了什么?
【问题讨论】: