《操作系统》的实验代码。
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

326 lignes
12 KiB

  1. #! /usr/bin/env python
  2. import sys
  3. from optparse import OptionParser
  4. import random
  5. # finds the highest nonempty queue
  6. # -1 if they are all empty
  7. def FindQueue():
  8. q = hiQueue
  9. while q > 0:
  10. if len(queue[q]) > 0:
  11. return q
  12. q -= 1
  13. if len(queue[0]) > 0:
  14. return 0
  15. return -1
  16. def LowerQueue(currJob, currQueue, issuedIO):
  17. if currQueue > 0:
  18. # in this case, have to change the priority of the job
  19. job[currJob]['currPri'] = currQueue - 1
  20. if issuedIO == False:
  21. queue[currQueue-1].append(currJob)
  22. job[currJob]['ticksLeft'] = quantum[currQueue-1]
  23. else:
  24. if issuedIO == False:
  25. queue[currQueue].append(currJob)
  26. job[currJob]['ticksLeft'] = quantum[currQueue]
  27. def Abort(str):
  28. sys.stderr.write(str + '\n')
  29. exit(1)
  30. #
  31. # PARSE ARGUMENTS
  32. #
  33. parser = OptionParser()
  34. parser.add_option('-s', '--seed', default=0, help='the random seed',
  35. action='store', type='int', dest='seed')
  36. parser.add_option('-n', '--numQueues', help='number of queues in MLFQ (if not using -Q)', default=3,
  37. action='store', type='int', dest='numQueues')
  38. parser.add_option('-q', '--quantum', help='length of time slice (if not using -Q)', default=10,
  39. action='store', type='int', dest='quantum')
  40. parser.add_option('-Q', '--quantumList', help='length of time slice per queue level, specified as x,y,z,... where x is the quantum length for the highest priority queue, y the next highest, and so forth',
  41. default='', action='store', type='string', dest='quantumList')
  42. parser.add_option('-j', '--numJobs', default=3, help='number of jobs in the system',
  43. action='store', type='int', dest='numJobs')
  44. parser.add_option('-m', '--maxlen', default=100, help='max run-time of a job (if randomly generating)',
  45. action='store', type='int', dest='maxlen')
  46. parser.add_option('-M', '--maxio', default=10, help='max I/O frequency of a job (if randomly generating)',
  47. action='store', type='int', dest='maxio')
  48. parser.add_option('-B', '--boost', default=0, help='how often to boost the priority of all jobs back to high priority',
  49. action='store', type='int', dest='boost')
  50. parser.add_option('-i', '--iotime', default=5, help='how long an I/O should last (fixed constant)',
  51. action='store', type='int', dest='ioTime')
  52. parser.add_option('-S', '--stay', default=False, help='reset and stay at same priority level when issuing I/O',
  53. action='store_true', dest='stay')
  54. parser.add_option('-I', '--iobump', default=False, help='if specified, jobs that finished I/O move immediately to front of current queue',
  55. action='store_true', dest='iobump')
  56. parser.add_option('-l', '--jlist', default='', help='a comma-separated list of jobs to run, in the form x1,y1,z1:x2,y2,z2:... where x is start time, y is run time, and z is how often the job issues an I/O request',
  57. action='store', type='string', dest='jlist')
  58. parser.add_option('-c', help='compute answers for me', action='store_true', default=False, dest='solve')
  59. (options, args) = parser.parse_args()
  60. random.seed(options.seed)
  61. # MLFQ: How Many Queues
  62. numQueues = options.numQueues
  63. quantum = {}
  64. if options.quantumList != '':
  65. # instead, extract number of queues and their time slic
  66. quantumLengths = options.quantumList.split(',')
  67. numQueues = len(quantumLengths)
  68. qc = numQueues - 1
  69. for i in range(numQueues):
  70. quantum[qc] = int(quantumLengths[i])
  71. qc -= 1
  72. else:
  73. for i in range(numQueues):
  74. quantum[i] = int(options.quantum)
  75. hiQueue = numQueues - 1
  76. # MLFQ: I/O Model
  77. # the time for each IO: not great to have a single fixed time but...
  78. ioTime = int(options.ioTime)
  79. # This tracks when IOs and other interrupts are complete
  80. ioDone = {}
  81. # This stores all info about the jobs
  82. job = {}
  83. # seed the random generator
  84. random.seed(options.seed)
  85. # jlist 'startTime,runTime,ioFreq:startTime,runTime,ioFreq:...'
  86. jobCnt = 0
  87. if options.jlist != '':
  88. allJobs = options.jlist.split(':')
  89. for j in allJobs:
  90. jobInfo = j.split(',')
  91. if len(jobInfo) != 3:
  92. sys.stderr.write('Badly formatted job string. Should be x1,y1,z1:x2,y2,z2:...\n')
  93. sys.stderr.write('where x is the startTime, y is the runTime, and z is the I/O frequency.\n')
  94. exit(1)
  95. assert(len(jobInfo) == 3)
  96. startTime = int(jobInfo[0])
  97. runTime = int(jobInfo[1])
  98. ioFreq = int(jobInfo[2])
  99. job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue], 'startTime':startTime,
  100. 'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
  101. 'firstRun':-1}
  102. if startTime not in ioDone:
  103. ioDone[startTime] = []
  104. ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
  105. jobCnt += 1
  106. else:
  107. # do something random
  108. for j in range(options.numJobs):
  109. startTime = 0
  110. runTime = int(random.random() * options.maxlen)
  111. ioFreq = int(random.random() * options.maxio)
  112. job[jobCnt] = {'currPri':hiQueue, 'ticksLeft':quantum[hiQueue], 'startTime':startTime,
  113. 'runTime':runTime, 'timeLeft':runTime, 'ioFreq':ioFreq, 'doingIO':False,
  114. 'firstRun':-1}
  115. if startTime not in ioDone:
  116. ioDone[startTime] = []
  117. ioDone[startTime].append((jobCnt, 'JOB BEGINS'))
  118. jobCnt += 1
  119. numJobs = len(job)
  120. print 'Here is the list of inputs:'
  121. print 'OPTIONS jobs', numJobs
  122. print 'OPTIONS queues', numQueues
  123. for i in range(len(quantum)-1,-1,-1):
  124. print 'OPTIONS quantum length for queue %2d is %3d' % (i, quantum[i])
  125. print 'OPTIONS boost', options.boost
  126. print 'OPTIONS ioTime', options.ioTime
  127. print 'OPTIONS stayAfterIO', options.stay
  128. print 'OPTIONS iobump', options.iobump
  129. print '\n'
  130. print 'For each job, three defining characteristics are given:'
  131. print ' startTime : at what time does the job enter the system'
  132. print ' runTime : the total CPU time needed by the job to finish'
  133. print ' ioFreq : every ioFreq time units, the job issues an I/O'
  134. print ' (the I/O takes ioTime units to complete)\n'
  135. print 'Job List:'
  136. for i in range(numJobs):
  137. print ' Job %2d: startTime %3d - runTime %3d - ioFreq %3d' % (i, job[i]['startTime'],
  138. job[i]['runTime'], job[i]['ioFreq'])
  139. print ''
  140. if options.solve == False:
  141. print 'Compute the execution trace for the given workloads.'
  142. print 'If you would like, also compute the response and turnaround'
  143. print 'times for each of the jobs.'
  144. print ''
  145. print 'Use the -c flag to get the exact results when you are finished.\n'
  146. exit(0)
  147. # initialize the MLFQ queues
  148. queue = {}
  149. for q in range(numQueues):
  150. queue[q] = []
  151. # TIME IS CENTRAL
  152. currTime = 0
  153. # use these to know when we're finished
  154. totalJobs = len(job)
  155. finishedJobs = 0
  156. print '\nExecution Trace:\n'
  157. while finishedJobs < totalJobs:
  158. # find highest priority job
  159. # run it until either
  160. # (a) the job uses up its time quantum
  161. # (b) the job performs an I/O
  162. # check for priority boost
  163. if options.boost > 0 and currTime != 0:
  164. if currTime % options.boost == 0:
  165. print '[ time %d ] BOOST ( every %d )' % (currTime, options.boost)
  166. # remove all jobs from queues (except high queue)
  167. for q in range(numQueues-1):
  168. for j in queue[q]:
  169. if job[j]['doingIO'] == False:
  170. queue[hiQueue].append(j)
  171. queue[q] = []
  172. # print 'BOOST: QUEUES look like:', queue
  173. # change priority to high priority
  174. # reset number of ticks left for all jobs (XXX just for lower jobs?)
  175. # add to highest run queue (if not doing I/O)
  176. for j in range(numJobs):
  177. # print '-> Boost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
  178. if job[j]['timeLeft'] > 0:
  179. # print '-> FinalBoost %d (timeLeft %d)' % (j, job[j]['timeLeft'])
  180. job[j]['currPri'] = hiQueue
  181. job[j]['ticksLeft'] = quantum[hiQueue]
  182. # print 'BOOST END: QUEUES look like:', queue
  183. # check for any I/Os done
  184. if currTime in ioDone:
  185. for (j, type) in ioDone[currTime]:
  186. q = job[j]['currPri']
  187. job[j]['doingIO'] = False
  188. print '[ time %d ] %s by JOB %d' % (currTime, type, j)
  189. if options.iobump == False:
  190. queue[q].append(j)
  191. else:
  192. queue[q].insert(0, j)
  193. # now find the highest priority job
  194. currQueue = FindQueue()
  195. if currQueue == -1:
  196. print '[ time %d ] IDLE' % (currTime)
  197. currTime += 1
  198. continue
  199. #print 'FOUND QUEUE: %d' % currQueue
  200. #print 'ALL QUEUES:', queue
  201. # there was at least one runnable job, and hence ...
  202. currJob = queue[currQueue][0]
  203. if job[currJob]['currPri'] != currQueue:
  204. Abort('currPri[%d] does not match currQueue[%d]' % (job[currJob]['currPri'], currQueue))
  205. job[currJob]['timeLeft'] -= 1
  206. job[currJob]['ticksLeft'] -= 1
  207. if job[currJob]['firstRun'] == -1:
  208. job[currJob]['firstRun'] = currTime
  209. runTime = job[currJob]['runTime']
  210. ioFreq = job[currJob]['ioFreq']
  211. ticksLeft = job[currJob]['ticksLeft']
  212. timeLeft = job[currJob]['timeLeft']
  213. print '[ time %d ] Run JOB %d at PRIORITY %d [ TICKSLEFT %d RUNTIME %d TIMELEFT %d ]' % (currTime, currJob, currQueue, ticksLeft, runTime, timeLeft)
  214. if timeLeft < 0:
  215. Abort('Error: should never have less than 0 time left to run')
  216. # UPDATE TIME
  217. currTime += 1
  218. # CHECK FOR JOB ENDING
  219. if timeLeft == 0:
  220. print '[ time %d ] FINISHED JOB %d' % (currTime, currJob)
  221. finishedJobs += 1
  222. job[currJob]['endTime'] = currTime
  223. # print 'BEFORE POP', queue
  224. done = queue[currQueue].pop(0)
  225. # print 'AFTER POP', queue
  226. assert(done == currJob)
  227. continue
  228. # CHECK FOR IO
  229. issuedIO = False
  230. if ioFreq > 0 and (((runTime - timeLeft) % ioFreq) == 0):
  231. # time for an IO!
  232. print '[ time %d ] IO_START by JOB %d' % (currTime, currJob)
  233. issuedIO = True
  234. desched = queue[currQueue].pop(0)
  235. assert(desched == currJob)
  236. job[currJob]['doingIO'] = True
  237. # this does the bad rule -- reset your tick counter if you stay at the same level
  238. if options.stay == True:
  239. job[currJob]['ticksLeft'] = quantum[currQueue]
  240. # add to IO Queue: but which queue?
  241. futureTime = currTime + ioTime
  242. if futureTime not in ioDone:
  243. ioDone[futureTime] = []
  244. ioDone[futureTime].append((currJob, 'IO_DONE'))
  245. # print 'NEW IO EVENT at ', futureTime, ' is ', ioDone[futureTime]
  246. # CHECK FOR QUANTUM ENDING AT THIS LEVEL
  247. if ticksLeft == 0:
  248. # print '--> DESCHEDULE %d' % currJob
  249. if issuedIO == False:
  250. # print '--> BUT IO HAS NOT BEEN ISSUED (therefor pop from queue)'
  251. desched = queue[currQueue].pop(0)
  252. assert(desched == currJob)
  253. # move down one queue! (unless lowest queue)
  254. LowerQueue(currJob, currQueue, issuedIO)
  255. # print out statistics
  256. print ''
  257. print 'Final statistics:'
  258. responseSum = 0
  259. turnaroundSum = 0
  260. for i in range(numJobs):
  261. response = job[i]['firstRun'] - job[i]['startTime']
  262. turnaround = job[i]['endTime'] - job[i]['startTime']
  263. print ' Job %2d: startTime %3d - response %3d - turnaround %3d' % (i, job[i]['startTime'],
  264. response, turnaround)
  265. responseSum += response
  266. turnaroundSum += turnaround
  267. print '\n Avg %2d: startTime n/a - response %.2f - turnaround %.2f' % (i,
  268. float(responseSum)/numJobs,
  269. float(turnaroundSum)/numJobs)
  270. print '\n'