问题描述:
给定n个程序,每种程序有五种操作,分别为 var = constant(赋值),print var (打印), lock, unlock,end。
变量用小写字母表示,初始化为0,为程序所公有(一个程序里对某个变量修改可以会影响其他程序里的这个变量),
常数小于100(也就是说最多两位数)。
每个时刻都只能有一个程序处于运行状态,其他的都在等待,上述五种操作用时分别是t1, t2, t3, t4, t5。运行中的程序,
每次最多能运行q个时间,当q个时间被用完后,它会被放在等待队列的尾部,然后再从首部取出一个程序运行,初始等待队列按输入顺序,但是lock和unlock会改变顺序,它们总是成对出现,不会出现嵌套。如果某个程序已经执行了lock,后面还有程序执行lock,那么这个程序就会马上被放到一个阻止队列的尾部(当然如果运行时间还没用完也就浪费了)。当unlock结束后,阻止队列中的第一个程序进入等待队列的首部。
输入n, t1, t2, t3, t4, t5,Q以及n个程序,按照时间顺序输出所以print 语句的程序编号和结果。
提示:用双端队列deque模拟“等待队列”,用队列queue模拟“阻止队列”。
代码展示:
// Concurrency Simulator
// @Author Willy Qi
#include<cstdio>
#include<queue>
#include<cstring>
#include<cstdlib>
#include<cctype>
using namespace std;
const int maxRow = 1000; //所有程序总行数的最大值
deque<int> readyQueue; //等待队列 (双端队列)
queue<int> lockQueue; //阻塞队列
char program[maxRow][10]; //存储所有程序的语句
int n, t[5], Q, Pointer[maxRow]; // n:程序数 ;t[]:语句单位时间;Q:配额;Pointer[]:记录每个程序的首地址在program的行数;
bool locked;
int var[26]; // 用单个字母表示变量,最多有26个变量
void run(int i){
int q = Q; //配额
while(q > 0) {
char *p = program[Pointer[i]]; //第 i 个程序的指针
switch(p[2]) {
case '=': // "* = 1"赋值操作
var[p[0] - 'a'] = isdigit(p[5]) ? (p[4] - '0') * 10 + p[5] - '0' : p[4] - '0';
q -= t[0];
break;
case 'i': // print操作
printf("%d: %d\n", i+1, var[p[6] - 'a']); //输出变量
q -= t[1];
break;
case 'c': // lock操作
if(locked) { lockQueue.push(i); return; } //当其他程序执行lock时,如果被lock,该程序被放到阻塞队列 ,释放执行权
locked = true;
q -= t[2];
break;
case 'l': // unlock操作
locked = false;
if(!lockQueue.empty()) {
int id2 = lockQueue.front(); lockQueue.pop();
readyQueue.push_front(id2); //将阻塞队列队首放到双端队列的首部
}
q -= t[3];
break;
case 'd': // end操作
return;
}
Pointer[i]++; //下一条语句
}
readyQueue.push_back(i);
}
int main(){
int Times; //模拟的次数
printf("请输入模拟次数\n");
scanf("%d",&Times);
while(Times--){
printf("请输入程序数,t1,t2,t3,t4,t5,配额Q\n");
scanf("%d %d %d %d %d %d %d\n", &n, &t[0], &t[1], &t[2], &t[3], &t[4], &Q);
memset(var,0,sizeof(var));
int line = 0; //行数
for(int i = 0; i < n; i++) {
fgets(program[line++], maxRow, stdin);
Pointer[i] = line - 1; //Pointer[]:记录每个程序的首地址
while(program[line-1][2] != 'd')
fgets(program[line++], maxRow, stdin);
readyQueue.push_back(i);
}
locked = false;
while(!readyQueue.empty()){
int id = readyQueue.front(); readyQueue.pop_front();
run(id);
}
if(Times) printf("\n");
}
return 0;
}
参考用例:(出自https://blog.youkuaiyun.com/sinat_38816924/article/details/82846302)