Reputation: 1111
I'm writing a program to simulate a CPU scheduler. As such, I'm implementing a doubly linked list to use as a ready queue. Whenever a new process is added, a process control block (PCB) is created and added to the ready queue. Each PCB has a unique PID given to it. As such, I increment the PID by 1 whenever a new PCB is added.
pid += 1;
currentDevices[0].enqueuePCB(pid);
//currentDevices[0] represents the ready queue. There are other queues as well
This is my enqueuePCB function:
void device::enqueuePCB(int num)
{
pcb* newPCB = new pcb();
newPCB -> pid = num;
newPCB -> next = NULL;
newPCB -> prev = NULL;
if (head == NULL)
{
head = tail = newPCB;
queueLength += 1;
}
else
{
pcb* temp = tail;
newPCB -> next = tail;
temp -> prev = newPCB;
tail = newPCB;
queueLength += 1;
}
}
and my print function
void device::snapReadyQueue()
{
pcb* temp = head;
cout << "PID: ";
while (temp != NULL)
{
cout << temp -> pid << " ";
temp = temp -> prev;
}
cout << endl;
}
When I tested out my program, adding just one PCB and printing results in a a blank "PiD: ". However, once I started adding more PCB's and printing, I actually can retrieve the PIDs of the other PCBs. For example, adding 2 more PCB after the first and printing will get me
PID: 2 3
The 1 is missing and I don't understand why. I looked through my if else statement for enqueue and it seems to make sense. I've also tried using a singly linked list, but it doesn't work.
Update After a bit of testing, I realized it might have to do with an if-else statement I use prior to initializing the queue.
if (processCount == 0)
{
cout << "Currently no processes in the ready queue.\nAvailable commands: A: ";
cin >> call;
if (call == "A")
{
pid = 1;
currentDevices[0].enqueuePCB(pid);
processCount += 1;
run();
}
}
else
{
cout << "Please enter call: ";
cin >> call;
if (call == "A")
{
pid += 1;
currentDevices[0].enqueuePCB(pid);
processCount += 1;
run();
}
I've tried printing just the head when I enqueued the first time, and my program crashes. Yet when I add the second PCB in, the head is pointing to PID 2.
Upvotes: 1
Views: 156
Reputation: 591
Are you setting the head and tail fields to NULL in your constructor? This could cause issues inside of device::enqueuePCB if they are not.
Upvotes: 1
Reputation: 1256
I think that the code for adding an element to the list is wrong, You say:
pcb* temp = tail;
newPCB -> next = tail;
temp -> prev = newPCB;
tail = newPCB;
queueLength += 1;
Assuming that tail is a pointer to the last element of the list we can track what is going on here. Let's forget about temp
right now, You tell the newPCB
that its next element is the tail (the current last element). Next you tell the tail
that its predecessor is the newPCB
and after that you make the newPCB
the tail. Therfore, the tail is the newPCB
, its previous element is NULL
but it's next element is what was the tail
before. I think what you mean is this:
tail -> next = newPCB;
newPCB -> prev = tail;
tail = newPCB;
Upvotes: 2