Search code examples
c++segmentation-faultcpuschedulinground-robin

Round robin scheduling algorithm has infinite loop


I am writing algorithm for round robin CPU scheduling and I have used vector as ready queue.

But when I run the code the initial value of i = *(vector.begin()) should be zero and next time i has another value according to code , as I did vector.push_back(0) but when I used a debugging statement it shows value of i = 5 and infinite times . Hence, I cannot have waiting time as output.

Here is the code and screenshot of output:-

Here is the code:

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int a[5],w[5],b[5],c[5],x[5],tat[5],i,j,complete=0,t=0,q,y=0; //a[] is arrival time b[] is burst time w[] waitingtime q=time slice c[] is completion time
    vector<int> v;     // using this vector as a ready queue which takes indices of processes
    v.push_back(0);
    cout<<"enter the value of quanta";
    cin>>q;
    cout<<"enter values of arrival time";
    for(i=0;i<5;i++)
    {
        cin>>a[i];
    }
    cout<<"enter values of burst time";
    for(i=0;i<5;i++)
    {
        cin>>b[i];
    }
    for(i=0;i<5;i++)
    x[i]=b[i];    //burst time keeps on changing acc to time slice so store initial burst times in array x

    while(complete!=5)     //complete denotes number of processes
    {
            i == *(v.begin());     //first process should be p0 i am considering it to give arrival time = 0
            cout<<i<<endl;
            if(a[i]<=t && b[i]>0)
            {
                for(j=1;j<=q;j++)
                {
                    b[i]--;
                    t++;      //whats the current time since cpu is running

                    if(b[i]==0)           //if just 1sec of bt of a process is left so it will come out of loop after being reduced by 1
                    break;
                }
                for(j=i+1;j<5;j++)          //to check which processes have arrived and push them in ready queue
                {
                    if(a[j]<=t && a[j]>y)
                       {  v.push_back(j);
                            y=a[j];
                       }
                }
                if(b[i] == 0)
                {
                    complete++;
                    c[i] = t;
                    w[i] = c[i] - a[i] - x[i];
                    tat[i] = c[i] - a[i];
                    v.erase(v.begin());         //remove the index of this process as it is no longer required
                }
                else                         // put the process to the last of ready queue if not completed
                {
                    v.push_back(i);
                    v.erase(v.begin());
                }
            }
        }

for(i=0;i<5;i++)
cout<<w[i]<<endl;  //display waiting times

}

Solution

  • This does not work:

    i == *(v.begin());
    

    You are comparing i, not setting it. Replace it with:

    i = *(v.begin());