Skip to content

Instantly share code, notes, and snippets.

@lawrencejones
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lawrencejones/9196650 to your computer and use it in GitHub Desktop.
Save lawrencejones/9196650 to your computer and use it in GitHub Desktop.
Implements priority donation according to the Imperial Pintos Specification (based on thread niceness and recent cpu time), using Round Robin ordering of threads
PRI_MAX = 63
RUN_TIME = 36/4
TIMER_INTERVAL = 4
TICKS_PER_SEC = 100
crrt = null
ticks = 0
create_thread = (name, nice, pri = PRI_MAX) ->
{ name: name, p: pri, n: nice, rcpu: 0 }
threads = [
create_thread 'a', 0, 63
create_thread 'b', 1, 61
create_thread 'c', 2, 59
].sort (a,b) -> b.p - a.p
sorted_threads = ->
threads[..].sort (a,b) ->
if a.name < b.name then return -1
else if a.name > b.name then return 1 else return 0
space = (str, length) ->
str = str.toString().trim()
length -= str.length
str + (null for s in [0..length]).join ' '
print_key = (key, length) ->
vals = []
for t in do sorted_threads
vals.push t[key]
space vals.join('/'), length
calc_priority = (t) ->
t.p = Math.floor (PRI_MAX - (t.rcpu / 4) - (t.n * 2))
calc_load_avg = -> (59/60)*load_avg + (1/60)*threads.length
tick_second = ->
do calc_load_avg
for t in threads
t.rcpu = (2*load_avg)/(2*load_avg + 1)*t.rcpu + t.n
next_thread = ->
found = false
threads = [].concat threads.reduce(((a,c) ->
a[2* +(c.p < crrt.p)].push c if c != crrt; a
), [[],crrt,[]])...
for t in threads
if t.p >= crrt.p then return t
tick = ->
if ((ticks += TIMER_INTERVAL)/TIMER_INTERVAL % TICKS_PER_SEC) == 0
do tick_second
(crrt ?= threads[0]).rcpu += 4
for t in threads
calc_priority t
crrt = do next_thread
print_row = (crrt_name) ->
console.log " #{space ticks, 3} | #{print_key 'rcpu', 10} | " +
"#{print_key 'p', 9} | #{crrt_name.toUpperCase()}"
ticks = 0
console.log " Timer | Rcpu | Pri | Thread\n" +
'-------------------------------------------------'
for _ in [0..RUN_TIME]
print_row crrt?.name || '-'
do tick
Timer | Rcpu | Pri | Thread
-------------------------------------------------
0 | 0/0/0 | 63/61/59 | -
4 | 4/0/0 | 62/61/59 | A
8 | 8/0/0 | 61/61/59 | B
12 | 8/4/0 | 61/60/59 | A
16 | 12/4/0 | 60/60/59 | B
20 | 12/8/0 | 60/59/59 | A
24 | 16/8/0 | 59/59/59 | C
28 | 16/8/4 | 59/59/58 | B
32 | 16/12/4 | 59/58/58 | A
36 | 20/12/4 | 58/58/58 | C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment