並行程序模擬(Concurrency Simulator, ACM/ICPC World Finals 1991,Uva210)

任務介紹

你的任務是模擬n個程序的並行運算。(按照輸入編號爲1~n)的並行執行。c++

代碼實現

#define LOCAL
#include<bits/stdc++.h>
using namespace std;
int main(){
    #ifdef LOCAL
    freopen("data.in","r",stdin);
    freopen("data.out","w",stdout);
    #endif // LOCAL
    int n,t[5],Q;
    scanf("%d%d%d%d%d%d%d",&n,&t[0],&t[1],&t[2],&t[3],&t[4],&Q);
    unordered_map<char,int>variable;//變量與其值的映射關係
    deque<int>block,wait;//阻塞隊列、等待隊列
    bool lock=false;//鎖
    vector<deque<string>>program(n+1);//每一個程序
    for(int i=1;i<=n;++i){//讀取每一個程序代碼
        wait.push_back(i);//。初始等待隊列包含按輸入順序排列的各個程序
        string line;
        while(getline(cin,line)&&line!="end")
            program[i].push_back(line);
        program[i].push_back("end");
    }
    while(!wait.empty()){//等待隊列不空就繼續循環
        int cur=wait.front();//讀取當前運行的程序
        wait.pop_front();
        if(program[cur].empty())//當前程序已運行完畢,再也不執行任何操做
            continue;
        wait.push_back(cur);//將當前運行的程序插入到等待隊列末尾
        for(int time=0;time<Q;){//當前程序運行時間小於配額時繼續執行
            string s=program[cur].front();//讀取須要執行的指令
            program[cur].pop_front();//彈出隊首指令
            if(s[2]=='='){//是賦值指令
                variable[s[0]]=stoi(s.substr(4));//更新或插入變量及其對應值
                time+=t[0];//更新當前程序運行時間
            }else if(s[2]=='i'){//是print指令
                printf("%d: %d\n",cur,variable[s[6]]);//打印
                time+=t[1];//更新當前程序運行時間
            }else if(s[2]=='c'){//是lock指令
                if(lock){//已經上鎖了
                    program[cur].push_front(s);//當前指令從新壓回隊首
                    block.push_back(cur);//當前程序插入到阻塞隊列隊尾
                    wait.pop_back();//將當前程序從等待隊列末尾中刪除
                    break;//再也不執行其餘指令
                }//沒有上鎖過
                lock=true;//上鎖
                time+=t[2];//更新當前程序運行時間
            }else if(s[2]=='l'){//unlock指令
                lock=false;//解除上鎖
                time+=t[3];//更新當前程序運行時間
                if(!block.empty()){//阻塞隊列不空
                    wait.push_front(block.front());//將阻塞隊列隊首程序插入到等待隊列隊首
                    block.pop_front();//彈出阻塞隊列隊首程序
                }
            }else if(s[2]=='d')//end指令
                break;//直接跳出循環
        }
    }
    return 0;
}
相關文章
相關標籤/搜索