c - 信号量和互斥循环
问题描述
我有两个函数,我使用信号量和互斥锁来解决经典的睡眠理发师问题。但是当我运行程序时,程序永远不会结束。
功能一:TA的动作(理发师举例)
void *teaching_assistant()
{
printf("\t<-- TA opened his office\n");
printf("\t<-- TA waiting for student\n");
while(1){
// If there is waiting students
if(waiting_students > 0){
ta_sleep_flag = 0;
sem_wait(&sem_stu);
pthread_mutex_lock(&mtx);
// TA giving advice to student
printf("\t<-- TA starts advising session\n");
num_chairs[next_teaching_position] = 0;
waiting_students--;
next_teaching_position = (next_teaching_position + 1) % NUM_MAX_CHAIR;
sleep(adviceperiod);
pthread_mutex_unlock(&mtx);
sem_post(&sem_ta);
}
// If there is no waiting student
else{
if(ta_sleep_flag == 0){
printf("\t<-- TA finished advising, taking a short nap\n");
ta_sleep_flag = 1;
sleep(napperiod);
sem_post(&sem_ta);
}
}
}
}
功能2:学生的行为(理发师示例的客户)
void *student(void *student_id)
{
int id_student = (int *)student_id;
printf("std<%d> entered lab\n", id_student);
while(1){
// If there is a waiting student, continue waiting
if(waiting_status(id_student) == 1){ continue; }
// Student is programming
printf("std<%d> programming for %d units\n", id_student, workperiod);
sleep(workperiod);
pthread_mutex_lock(&mtx);
printf("std<%d> checking TA office\n", id_student);
//found available cahir
if(waiting_students < NUM_MAX_CHAIR){
num_chairs[next_seating_position] = id_student;
waiting_students++;
chair++;
printf("std<%d> entered TA office; %d seats occupied\n", id_student, chair);
next_seating_position = (next_seating_position + 1) % NUM_MAX_CHAIR;
pthread_mutex_unlock(&mtx);
// Wake TA if sleeping
sem_post(&sem_stu);
sem_wait(&sem_ta);
}
// Go drink coffe if there is no available seat
else{
pthread_mutex_unlock(&mtx);
sleep(coffeeperiod);
sem_post(&sem_stu);
}
}
}
我的预期输出是:
<--TA opened his office
<--TA waiting for a student
std <2145236736> entered lab
std <2145236736>programming for 10 units
std <2145236736> checking TA office
std <2145236736> entered TA office; 1 seats occupied
<--TA starts advising session
std <2145236736> asking questions
std <2145236736> leaving TA office
std <2145236736> signing off; active students= 0
<--TA finished advising, taking a short nap
<--TA signing off
但是当我编译代码时,我得到了无限循环。
解决方案
推荐阅读
- python - 确定 unicode 字符是否存在于 unicode 子集中
- c++ - 获取字符串大小的各种方法之间的比较
- python - plotly 4.1没有情节
- docker - Docker Image推送到谷歌容器注册表不起作用
- java - 请设置 JAVA_HOME 变量
- ios - 使用通用协议过滤子视图数组
- python - 错误:只能比较标记相同的 DataFrame 对象
- python - 如何修复 python 3.7 中的“RuntimeError: input(): lost sys.stdin”错误
- python - 使用布尔键值对将字符串转换为字典格式
- linux - Shell 命令显示不同的行为.. 在终端与运行 scipt