Operating System - Second Chance / Clock Page Replacement Algorithm



The page replacement algorithms are used decide which page to replace when a page fault occurs during memory management. In the last section, we discussed various page replacement algorithms like FIFO, LRU, Optimal, and LFU. This chapter will focus on explaining the Second Chance or Clock Page Replacement Algorithm.

Second Chance Page Replacement Algorithm

The Second Chance Page Replacement Algorithm, is an enhanced version of the FIFO page replacement algorithm. The main issue with the FIFO algorithm is that it may remove frequently used pages just because they were loaded earlier. To overcome this, the Second Chance algorithm gives pages a second chance before replacing them. This algorithm is also known as the Clock Page Replacement algorithm because of its circular structure.

In this algorithm, each page has a reference bit associated with it. When a page is accessed, its reference bit is set to 1. When a page needs to be replaced, the algorithm checks the reference bit of the pages in the order they were loaded (like FIFO). If the reference bit is 0, the page is replaced. If the reference bit is 1, the page is given a second chance and then its reference bit is cleared ( to ensure no third chance is given).

Steps of Second Chance Page Replacement Algorithm

To implement the Second Chance Page Replacement Algorithm, follow these steps −

  • Maintain a circular queue of pages in memory, same as that of FIFO algorithm.
  • Create a pointer that points to the oldest page in the queue.
  • For each page, create a reference bit (R) initialized to 0. When a page is accessed, set its reference bit (R) to 1.
  • When a page fault occurs and a page needs to be replaced, check the page pointed to by the pointer. If its reference bit (R) is 0, replace that page with the new page.
  • If the reference bit (R) is 1, give the page a second chance by clearing its reference bit (set R to 0) and move the pointer to the next page in the queue.
  • Repeat this process until a page with reference bit 0 is found.

Example of Second Chance Page Replacement Algorithm

Consider a system with 4 page frames and the following page reference string −

7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2

Let's see how the Second Chance page replacement algorithm works with this reference string:

Page Frame Page Number Reference Bit (R)
Frame 0 7 1
Frame 1 0 1
Frame 2 1 1
Frame 3 2 1

We start with a FIFO queue of pages. All pages have been referenced, so their reference bits (R) are 1. The pointer is at the oldest page, "Page 7". An incoming request for "Page 3" causes a page fault. The algorithm checks the pages in the order they were loaded −

  • Since the reference bit of Page 7 is 1, it is given a second chance. The reference bit is cleared (set to 0), and the pointer moves to the next page, "Page 0".
  • The reference bit of Page 0 is also 1, so it is given a second chance as well. Its reference bit is cleared, and the pointer moves to Page 1.
  • This process continues until a page with a reference bit of 0 is found. If all pages have been given a second chance (i.e., their reference bits are cleared), the algorithm will replace the first page it encounters.

Implement Second Chance Page Replacement Algorithm

The section below provides a simple implementation of the Second Chance Page Replacement Algorithm in Python, C++, and Java.

class SecondChance:
    def __init__(self, frames):
        self.frames = frames
        self.page_frames = []
        self.reference_bits = []
        self.pointer = 0

    def access_page(self, page):
        if page in self.page_frames:
            index = self.page_frames.index(page)
            self.reference_bits[index] = 1
            return

        if len(self.page_frames) < self.frames:
            self.page_frames.append(page)
            self.reference_bits.append(1)
        else:
            while True:
                if self.reference_bits[self.pointer] == 0:
                    self.page_frames[self.pointer] = page
                    self.reference_bits[self.pointer] = 1
                    self.pointer = (self.pointer + 1) % self.frames
                    break
                else:
                    self.reference_bits[self.pointer] = 0
                    self.pointer = (self.pointer + 1) % self.frames
# Example usage
sc = SecondChance(4)
page_reference_string = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
for page in page_reference_string:
    sc.access_page(page)
    print(f"Page Frames: {sc.page_frames}, Reference Bits: {sc.reference_bits}")

The output of the above code will be −

Page Frames: [7], Reference Bits: [1]
Page Frames: [7, 0], Reference Bits: [1, 1]
Page Frames: [7, 0, 1], Reference Bits: [1, 1, 1]
Page Frames: [7, 0, 1, 2], Reference Bits: [1, 1, 1, 1]
Page Frames: [7, 0, 1, 2], Reference Bits: [1, 1, 1, 1]
Page Frames: [3, 0, 1, 2], Reference Bits: [1, 0, 1, 1]
....
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class SecondChance {
public: 
    int frames;
    vector<int> page_frames;
    vector<int> reference_bits;
    int pointer;

    SecondChance(int f) : frames(f), pointer(0) {}

    void access_page(int page) {
        auto it = find(page_frames.begin(), page_frames.end(), page);
        
        if (it != page_frames.end()) {
            int index = distance(page_frames.begin(), it);
            reference_bits[index] = 1;
            return;
        }

        if (page_frames.size() < frames) {
            page_frames.push_back(page);
            reference_bits.push_back(1);
        } else {
            while (true) {
                if (reference_bits[pointer] == 0) {
                    page_frames[pointer] = page;
                    reference_bits[pointer] = 1;
                    pointer = (pointer + 1) % frames;
                    break;
                } else {
                    reference_bits[pointer] = 0;
                    pointer = (pointer + 1) % frames;
                }
            }
        }
    }
};

int main() {
    SecondChance sc(4);
    vector<int> page_reference_string = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};
    
    for (int page : page_reference_string) {
        sc.access_page(page);
        cout << "Page Frames: ";
        for (int p : sc.page_frames) cout << p << " ";
        cout << ", Reference Bits: ";
        for (int r : sc.reference_bits) cout << r << " ";
        cout << endl;
    }
    return 0;
}

The output of the above code will be −

Page Frames: 7 , Reference Bits: 1
Page Frames: 7 0 , Reference Bits: 1 1
Page Frames: 7 0 1 , Reference Bits: 1 1 1
Page Frames: 7 0 1 2 , Reference Bits: 1 1 1 1
Page Frames: 7 0 1 2 , Reference Bits: 1 1 1 1
Page Frames: 3 0 1 2 , Reference Bits: 1 0 1 1
....
import java.util.ArrayList;
import java.util.List;

class SecondChance {
    private int frames;
    private List<Integer> pageFrames;
    private List<Integer> referenceBits;
    private int pointer;

    public SecondChance(int f) {
        this.frames = f;
        this.pageFrames = new ArrayList<>();
        this.referenceBits = new ArrayList<>();
        this.pointer = 0;
    }

    public List<Integer> getPageFrames() {
        return pageFrames;
    }

    public List<Integer> getReferenceBits() {
        return referenceBits;
    }
    // ----------------------------------

    public void accessPage(int page) {
        if (pageFrames.contains(page)) {
            int index = pageFrames.indexOf(page);
            referenceBits.set(index, 1);
            return;
        }

        if (pageFrames.size() < frames) {
            pageFrames.add(page);
            referenceBits.add(1); // Usually new pages get a second chance immediately
        } else {
            while (true) {
                if (referenceBits.get(pointer) == 0) {
                    pageFrames.set(pointer, page);
                    referenceBits.set(pointer, 1); // Set bit to 1 for the new page
                    pointer = (pointer + 1) % frames;
                    break;
                } else {
                    referenceBits.set(pointer, 0); // Give second chance (set to 0)
                    pointer = (pointer + 1) % frames; // Move pointer
                }
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        SecondChance sc = new SecondChance(4); // 4 frames
        int[] pageReferenceString = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};

        System.out.println("Processing Page Reference String...");
        
        for (int page : pageReferenceString) {
            sc.accessPage(page);
            // FIX: Use the getter methods instead of direct access
            System.out.println("Accessed: " + page + 
                               " | Frames: " + sc.getPageFrames() + 
                               " | Ref Bits: " + sc.getReferenceBits());
        }
    }
}

The output of the above code will be −

Processing Page Reference String...
Accessed: 7 | Frames: [7] | Ref Bits: [1]
Accessed: 0 | Frames: [7, 0] | Ref Bits: [1, 1]
Accessed: 1 | Frames: [7, 0, 1] | Ref Bits: [1, 1, 1]
Accessed: 2 | Frames: [7, 0, 1, 2] | Ref Bits: [1, 1, 1, 1]
Accessed: 0 | Frames: [7, 0, 1, 2] | Ref Bits: [1, 1, 1, 1]
Accessed: 3 | Frames: [3, 0, 1, 2] | Ref Bits: [1, 0, 0, 0]
Accessed: 0 | Frames: [3, 0, 1, 2] | Ref Bits: [1, 1, 0, 0]
....

Conclusion

The Second Chance or Clock Page Replacement Algorithm is an improvement over the FIFO algorithm. The main idea here is to give pages a second chance before replacing them. This will help in reducing page faults as frequently used pages are less likely to be replaced. The algorithm uses a reference bit to track whether a page has been accessed recently. Overall, the Second Chance algorithm provides a good balance between simplicity and performance in page replacement strategies.

Advertisements