本文主要是介绍操作系统实验三:用PV操作实现司机售票员进程同步(C语言实现),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码如下:
driver_spy.cpp
#include<stdio.h>
#include<stdlib.h>int S1 = 0, S2 = 1, sum = 0;
char name[10] = "null";void driver(int s1, int s2, char name[]);
void busman(int s1, int s2, char name[]);
void p(int s, char name[]);
void v(int s, char name[]);
void addrecord();int main(){driver(S1, S2, "driver");busman(S1, S2, "busman");return 0;
}void driver(int s1, int s2, char name[])
{ printf("离站开车\n"); printf("正常行车\n");printf("到站停车\n"); v(s2, "driver"); //汽车到站,唤醒售票员开车门p(s1, "driver"); //初始S1=0,P(S1)后S1=-1,司机无法启动车辆,需等待售票员执行关门操作(V(S1)),需售票员关好门,唤醒司机,司机才能启动车辆 }
void busman(int s1, int s2, char name[])
{p(s2, "busman"); //售票员打开车门,需S2>0时。初始S2=0,售票员不能打开车门,需等司机执行V(S2)操作,唤醒售票员开门,售票员才能打开车门printf("开车门\n");printf("关车门\n");v(s1, "busman"); //售票员已关好车门,执行V(S1),唤醒司机启动车辆printf("售票\n");
}void p(int s, char name[]){s = s-1;while(1){if( s >= 0 ){if(name == "driver"){printf("P(S1)操作\n收到开车信号\n"); break;}if(name == "busman"){printf("P(S2)操作 - 收到开车门信号\n"); break;}break;}if(s < 0)if(name == "driver"){printf("P(S1)操作 - 司机进程阻塞,等待售票员进程发出开车信号\n"); busman(s, S2, "busman");}if(name == "busman"){printf("P(S2)操作 - 收到开车门信号\n");driver(S1, s, "driver");}}}
void v(int s, char name[]){s = s+1;while(1){if( s > 0 ){if(name = "driver")printf("V(S2)操作 - 发出开车门信号\n"); break;}if(s <= 0) if(name == "busman"){sum++;printf("V(S1)操作 - 发出开车信号\n售票\n");sum++;if(sum>2) //执行两次循环 exit(-1);driver(s, S2, "driver");} }
}
运行结果如图:
这篇关于操作系统实验三:用PV操作实现司机售票员进程同步(C语言实现)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!