操作系统实验:模拟生产者-消费者问题。自己写的作业,压根没用上老师上课讲的那些东西,只是用了一个信号量来控制。
web模拟生产者-消费者问题
结果如下:
缓冲区满:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>生产者-消费者模型</title>
<style>
#containerP {
width: 1500px;
height: 200px;
position: relative;
background: yellow;
}
#producer {
width: 100px;
height: 100px;
position: absolute;
background-color: red;
top: 50px;
left: 150px;
}
.pStart {
width: 80px;
height: 30px;
position: absolute;
top: 80px;
left: 30px;
}
.pStop {
width: 80px;
height: 30px;
position: absolute;
top: 80px;
left: 1240px;
}
#containerB {
width: 1500px;
height: 200px;
position: relative;
background:greenyellow;
}
#buffer {
width: 80px;
height: 30px;
position: absolute;
top: 80px;
left: 750px;
}
#containerC {
width: 1500px;
height: 200px;
position: relative;
background:yellow;
}
#consumer {
width: 100px;
height: 100px;
position: absolute;
background-color: red;
top: 50px;
left: 150px;
}
.cStart {
width: 80px;
height: 30px;
position: absolute;
top: 80px;
left: 30px;
}
.cStop {
width: 80px;
height: 30px;
position: absolute;
top: 80px;
left: 1240px;
}
</style>
</head>
<body onload = "show()">
<div id = "containerP">
<div>生产者:</div>
<div id = "producer"></div>
<button onclick = "produce()" class = "pStart">开始生产</button>
<button onclick = "stopPro()" class = "pStop">停止生产</button>
</div>
<div id = "containerB">
<div>缓冲池:</div>
<div id = "buffer"></div>
</div>
<div id = "containerC">
<div>消费者:</div>
<div id = "consumer"></div>
<button onclick = "consume()" class = "cStart">开始消费</button>
<button onclick = "stopCon()" class = "cStop">停止消费</button>
</div>
<script>
var count = 0;//缓冲区产品个数
var pos_pro = 150;
function show() {
document.getElementById("buffer").innerHTML = count;
if (count <= 0) {
alert("缓冲区为空,不能消费!");
}else if (count >= 5){
alert("缓冲区已满,不能生产!");
}
}
var flag_pro = true;//暂停标志
function stopPro() {
flag_pro = false;
}
function produce() {
flag_pro = true;
var e = document.getElementById("producer");
var id = setInterval(frame,25);
function frame() {
if (pos_pro == 1100 ){
pos_pro = 150;
count++;
show();
}else if (pos_pro < 1100 && flag_pro && count < 5){//缓冲区未满,仍可生产
pos_pro += 10;
e.style.left = pos_pro + "px";
}else if (!flag_pro || count == 5) {//缓冲区已满,不可生产
clearInterval(id);
}
}
}
var pos_con = 150;
var flag_con = true;//暂停标志
function stopCon() {
flag_con = false;
}
function consume() {
flag_con = true;
var e = document.getElementById("consumer");
var id = setInterval(frame,25);
function frame() {
if (pos_con == 1100){
pos_con = 150;
count--;
show();
}else if (pos_con < 1100 && flag_con && count > 0){//缓冲区未空,可以消费
pos_con += 10;
e.style.left = pos_con + "px";
}else if (!flag_con || count == 0) {
clearInterval(id);
}
}
}
</script>
</body>
</html>
请多多指教!