Question

In: Computer Science

P3 – Page Replacement Algorithms CS3310 Operating Systems Page Replacement: Complete the program that implements the...

P3 – Page Replacement Algorithms
CS3310 Operating Systems

Page Replacement:

Complete the program that implements the FIFO and LRU algorithms presented in the chapter and calculates the number of page faults generated given a particular reference string. Implement the replacement algorithms such that the number of page frames can vary. Assume that demand paging is used.

Required Modifications:

  • Implement LRU and FIFO algorithms
    • Add appropriate data structures and private helper methods to LRU.h and FIFO.h
    • Implement the insert() method in LRU.cpp and FIFO.cpp as well as any helper functions you specify in the header files.
  • ReplacementAlgorithm.h should not be modified.
  • testPR.cpp may be modified to facilitate testing and/or analysis. Comment appropriately.
    • You may want to modify the number of pages MAX_PAGE_NUMBER.
  • reference_string.txt is given as an example reference string that can be opened via the command line arguments. You must create at least one more interesting and representative reference string and use one of them in your testing and analysis. If an input file is not specified, a random sequence of page numbers is generated.

Extra Credit (+30%)

  • Create the OPT (optimal) replacement algorithm and compare its results with LRU & FIFO in your analysis. The implementation will have to be slightly different than the LRU & FIFO algorithm classes. If you make any changes to ReplacementAlgorithm.h or substantial changes to testPR.cpp, please be sure to document them appropriately

Project Code:

LRU.h:

#ifndef _LRU_H
#define _LRU_H

#include <iostream>
#include "ReplacementAlgorithm.h"

class LRU : public ReplacementAlgorithm {
public:
LRU(int numPageFrames);
void insert(int pageNumber) override;

private:
  
// data structure to store the int page frame list
//<data type> frameList;
};

#endif

LRU.cpp:

#include "LRU.h"

LRU::LRU(int numPageFrames) : ReplacementAlgorithm(numPageFrames) {
pageFaultCount = 0;
}

void LRU::insert(int pageNumber)
{
// Implement LRU page replacement algorithm
// Increment pageFaultCount if a page fault occurs

}

FIFO.h:

#ifndef _FIFO_H
#define _FIFO_H

#include <iostream>
#include "ReplacementAlgorithm.h"

class FIFO : public ReplacementAlgorithm {
public:
FIFO(int numPageFrames);
void insert(int pageNumber) override;

private:
// data structure to store the int page frame list
//<data type> frameList;
};

#endif

FIFO.cpp:

#include "FIFO.h"

FIFO::FIFO(int numPageFrames) : ReplacementAlgorithm(numPageFrames) {
pageFaultCount = 0;
}

void FIFO::insert(int pageNumber)
{
// Implement FIFO page replacement algorithm
// Increment pageFaultCount if a page fault occurs

}

reference_string.txt = 0 1 2 3 1 4 5 6 1 3 4 5 6 3 4 6 3 5 7 3 7 8 9 8 3 9

ReplacementAlgorithm.h:

#ifndef _REPLACEMENTALGORITHM_H
#define _REPLACEMENTALGORITHM_H

class ReplacementAlgorithm
{
public:
// numPageFrames - the number of physical page frames
ReplacementAlgorithm(int numPageFrames): pageFrameCount(numPageFrames) {};

// returns the number of page faults that occured
int getPageFaultCount() { return pageFaultCount; }

// pageNumber - the page number to be inserted
virtual void insert(int pageNumber) {};

protected:
int pageFaultCount;
int pageFrameCount;
};

testPR.cpp:
// Testing program for the page replacement algorithms.
//

#include <cstdlib>
#include <time.h>
#include <vector>
#include <iostream>
#include <string>
#include <fstream>

#include "ReplacementAlgorithm.h"
#include "LRU.h"
#include "FIFO.h"
// #include "OPT.h"

std::vector<int> referenceString;

const int MAX_PAGE_NUMBER = 100;

// testPR <reference string size> <number of page frames> [fileName]
// The "reference string size" parameter is ignored if a filename is provided.
int main(int argc, char **argv)
{
int count;
int numPageFrames;
bool useRefFile = false;
std::string fileName = "";
std::ifstream in;

srand((unsigned int)time(0));

if (argc < 3 || argc > 4){
std::cerr << "Usage: " << argv[0]
<< " <reference string size> <number of page frames> "
<< "[reference string filename]"
<< std::endl;
exit(1);
}

count = atoi(argv[1]);
numPageFrames = atoi(argv[2]);

// input reference string from file or just randomly generate
if (argc == 4){
useRefFile = true;

//open the input file
in.open(argv[3]);
if (!in.is_open()){
std::cerr << "Error opening file " << fileName
<< ". Exiting..." << std::endl;
exit(1);
}

int n;
while (!in.eof())
{
in >> n;
if (n >= 0 && n < MAX_PAGE_NUMBER){
referenceString.push_back(n);
}
}
in.close();
}
else {
for (int i = 0; i < count; i++){
referenceString.push_back(rand() % MAX_PAGE_NUMBER);
}
}

ReplacementAlgorithm * lru = new LRU(numPageFrames);
ReplacementAlgorithm * fifo = new FIFO(numPageFrames);

for (int i : referenceString) {
lru->insert(i);
fifo->insert(i);
}

std::cout << "LRU faults = " << lru->getPageFaultCount() << std::endl;
std::cout << "FIFO faults = " << fifo->getPageFaultCount() << std::endl;
return 0;
}

#endif // !PPD_REPLACEMENTALGORITHM_H

Solutions

Expert Solution

//C++ implementation of above algorithm

#include<bits/stdc++.h>

using namespace std;

// Function to find page faults using indexes

int pageFaults(int pages[], int n, int capacity)

{

    // To represent set of current pages. We use

    // an unordered_set so that we quickly check

    // if a page is present in set or not

    unordered_set<int> s;

    // To store least recently used indexes

    // of pages.

    unordered_map<int, int> indexes;

    // Start from initial page

    int page_faults = 0;

    for (int i=0; i<n; i++)

    {

        // Check if the set can hold more pages

        if (s.size() < capacity)

        {

            // Insert it into set if not present

            // already which represents page fault

            if (s.find(pages[i])==s.end())

            {

                s.insert(pages[i]);

                // increment page fault

                page_faults++;

            }

            // Store the recently used index of

            // each page

            indexes[pages[i]] = i;

        }

        // If the set is full then need to perform lru

        // i.e. remove the least recently used page

        // and insert the current page

        else

        {

            // Check if current page is not already

            // present in the set

            if (s.find(pages[i]) == s.end())

            {

                // Find the least recently used pages

                // that is present in the set

                int lru = INT_MAX, val;

                for (auto it=s.begin(); it!=s.end(); it++)

                {

                    if (indexes[*it] < lru)

                    {

                        lru = indexes[*it];

                        val = *it;

                    }

                }

                // Remove the indexes page

                s.erase(val);

                // insert the current page

                s.insert(pages[i]);

                // Increment page faults

                page_faults++;

            }

            // Update the current page index

            indexes[pages[i]] = i;

        }

    }

    return page_faults;

}

// Driver code

int main()

{

    int pages[] = {7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2};

    int n = sizeof(pages)/sizeof(pages[0]);

    int capacity = 4;

    cout << pageFaults(pages, n, capacity);

    return 0;

}


Related Solutions

Write a program that implements the FIFO, LRU, and Optimal page replacement algorithms presented in chapter...
Write a program that implements the FIFO, LRU, and Optimal page replacement algorithms presented in chapter 8 of your text. First generate a random page-reference string (this should be 20 entries long) where page numbers range from 0 to 9. Apply the random page-reference string to each algorithm, and record the number of page faults incurred by each algorithm. Implement the replacement algorithms so that the number of page frames goes from 1 to 7 and you must compute the...
Page Replacement Algorithms. Consider the following page reference stream and 3 page frames: 0 1 2...
Page Replacement Algorithms. Consider the following page reference stream and 3 page frames: 0 1 2 3 2 4 3 1 1 5 2 4 6 3 3 4 6 3 4 7. For the MIN, FIFO, and LRU algorithms, show the contents of the page frame after each reference, and then compute the total number of page faults, divided in to cold misses and other misses.
Write a C++ program that implements both the recursive binary and mergesort algorithms as described in...
Write a C++ program that implements both the recursive binary and mergesort algorithms as described in zyBooks sections 9.4 and 9.5. Prompt the user for the location of a sequence of numbers, via an external file or data entry by the user. If you choose data entry, prompt the user for the number of values and read them into a data structure of your choice. Then use the mergesort algorithm to sort them in ascending order. Finally, prompt for a...
Task: Write a program that implements several sorting algorithms and use it to demonstrate the comparative...
Task: Write a program that implements several sorting algorithms and use it to demonstrate the comparative performance of the algorithms for a variety of datasets. Background The skeleton program sorting.cpp contains a main function for testing the operation of several sort algorithms over various data sizes and dataset organisations. The program understands the following arguments: -i insertion sort -s selection sort (default) -q quicksort -a (already) sorted dataset -v reverse-sorted dataset -r random dataset (default) -n no sorting x generate...
Write an MSP430 assembly language program that implements the following 2 algorithms: 2) a macro called...
Write an MSP430 assembly language program that implements the following 2 algorithms: 2) a macro called "vdot" that calculates the "dot product" of two vectors "a" and "b", implemented as “arrays” (following the “C” language convention), of 3 elements. the macro should receive 2 pointers to the first element of each vector and return the result in R13.
Write a program that implements the follow disk scheduling algorithms. You can use C or Java...
Write a program that implements the follow disk scheduling algorithms. You can use C or Java for this assignment. FCFS SSTF SCAN C-SCAN LOOK C-LOOK Your program will service a disk with 5000 cylinders (numbered 0 to 4999). Your program will generate a random initial disk head position, as well as a random series of 1000 cylinder requests, and service them using each of the 6 algorithms listed above. Your program will report the total amount of head movement required...
Optimal and near-optimal process scheduling and page replacement algorithms. a) What is the theoretically best process...
Optimal and near-optimal process scheduling and page replacement algorithms. a) What is the theoretically best process scheduling algorithm? b) Do shortest job first and shortest remaining time first amount to the same thing or not? c) Can they be directly implemented? d) What do you consider the next best scheduling option, and how does it use the recent past to approximate the ideal case? e) Consider the analogous case in page replacement. What is the best possible choice of page...
List and define the alternative page fetch policies.   (0.5 point each) What are three replacement algorithms?...
List and define the alternative page fetch policies.   (0.5 point each) What are three replacement algorithms? (.333 points each) What is the purpose of the TLB?   (0.5 points)
Design a program in JAVA that allows you to experiment with different sort algorithms. The algorithms...
Design a program in JAVA that allows you to experiment with different sort algorithms. The algorithms are shell sort and quick sort. Assume that input data is stored in a text file. Experimenting with a prototype data (integers from 1 to 10) to ensure that your implementation works correctly and the results match expectations. The program will sort what is in the text file and print the amount of comparisons and exchanges for both algorithms.
Write a C++ program to compare those two searching algorithms and also compare two sorting algorithms....
Write a C++ program to compare those two searching algorithms and also compare two sorting algorithms. You need to modify those codes in the book/slides to have some counters to count the number of comparisons and number of swaps. In the main function, you should have an ordered array of 120integers in order to test searching algorithms, and the other two identical arrays of 120integers not in order to test sorting algorithms. Display all counters in the main functions.Counter for...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT