Skip to content

Instantly share code, notes, and snippets.

@TobleMiner
Last active May 25, 2016 13:52
Show Gist options
  • Save TobleMiner/62bdd0a5cd9d30ec4dd73e2f3a3988a9 to your computer and use it in GitHub Desktop.
Save TobleMiner/62bdd0a5cd9d30ec4dd73e2f3a3988a9 to your computer and use it in GitHub Desktop.
Dirty implementation of the second-chance algorithm
#!/usr/bin/env python
import sys
buffsize = 4
refstring = [0, 1, 2, 3, 1, 0, 4, 5, 1, 0, 1, 2, 6, 5, 2, 1, 0, 1, 2, 5]
if len(sys.argv) >= 3:
buffsize = int(sys.argv[1])
refstring = sys.argv[2].split()
class InMemoryPage():
def __init__(self, id):
self.id = id
self.guard = False
class LinkedObject():
def __init__(self, obj):
self.o = obj
self.next = None
self.prev = None
class FIFO():
def __init__(self, size):
self.size = size
self.head = None
self.tail = None
self.length = 0
def indexof(self, o):
i = 0
current = self.head
while current != None:
if current.o == o:
return i
i += 1
current = current.next
def enqueue(self, o):
obj = LinkedObject(o)
if self.head == None:
self.head = obj
self.tail = obj
self.length = 1
else:
if self.isfull():
self.dequeue()
self.enqueue(o)
else:
obj.next = self.head
self.head.prev = obj
self.head = obj
self.length += 1
def dequeue(self):
if self.tail == None:
return None
obj = self.tail.o
if self.tail != self.head:
self.tail.prev.next = None
else:
self.head = None
self.tail = self.tail.prev
self.length -= 1
return obj
def isfull(self):
return self.length == self.size
class SecondChance(FIFO):
def __init__(self, size):
super().__init__(size)
def findpage(self, i):
cur = self.head
while cur != None:
if cur.o.id == i:
return cur.o
cur = cur.next
return None
def getpage(self, i):
page = self.findpage(i)
if page:
print(self.tostring())
page.guard = True
return page
if self.isfull():
while self.tail.o.guard:
page = self.dequeue()
page.guard = False
self.enqueue(page)
page = InMemoryPage(i)
self.enqueue(page)
print(self.tostring() + ' F')
return page
def tostring(self):
s = ''
next = self.head
while next != None:
s += str(next.o.id) + ('+ ' if next.o.guard else ' ')
next = next.next
s += ''.join([' ' for a in range((self.size - self.length) * 3)])
return s
sc = SecondChance(buffsize)
for i in refstring:
sc.getpage(i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment