}
status = write(fileDescr,buf,26); if (status == -1) { printf(\ return 1; }
status = read(fileDescr, buf2, 26); if (status == -1) { printf(\ return 1; }
status = close(fileDescr); if (status == -1) { printf(\ return 1; }
unlink(\
printf(\
return 0; }
程序截图
由于程序没有打印出出错的标识,所以所有系统调用都成功完成 代码正确
4 LotteryScheduler
实现彩票调度类,这个类继承自PriorityScheduler类,最大的不同是,决定下一个执行的线程不是看优先级而是看彩票是否中奖,而且不能导致饥饿。等待的线程要将自己的彩票捐献给被等待的进程来增加它的彩票数量进而增加中奖的几率。这个调度程序在彩票是亿万时也能正常工作,所以不能保存彩票的指针。 (a) 设计思想
与其父类类似,也是引入一个ThreadState类用来把进程和彩票数量联系在一起,但是在得到有效优先级时,是把等待自己的队列中的进程的优先级和自己的优先级加起来,总的彩票数才是自己的优先级。而在nextThread()方法中,要先计算进程队列中总的彩票数(也就是所有进程的有效优先级的和),然后根据这个彩票数产生一个随机数,表示中奖的号码。由于不能保存彩票的指针,所以只能遍历队列,累加线程的有效优先级,当有效优先级的总和大于等于中奖号码表示这个线程中奖,这是利用概率中的随机原则将中奖转换为了累加。找到线程后将线程从队列中取出,将其返回。 (b) 源代码
public int getEffectivePriority() { effectivepriority=priority;
for(int i=0;i public KThread nextThread() { Lib.assertTrue(Machine.interrupt().disabled()); if(waitQueue.isEmpty()) return null; int alltickets=0; for(int i=0;i { ThreadState thread=waitQueue.get(i); alltickets=alltickets+thread.getEffectivePriority(); } int numOfWin=Lib.random(alltickets+1); int nowtickets=0; KThread winThread=null; ThreadState thread=null; for(int i=0;i nowtickets=nowtickets+thread.getEffectivePriority(); if(nowtickets>=numOfWin) {winThread=thread.thread; break; } } if(winThread!=null) waitQueue.remove(thread); return winThread; } (c) 程序截图 创建三个线程thread1,thread2,thread3,分别赋予优先级为1,2,7,thread3中调用了thread1.join()。运行之后,thread1得到了thread3的优先级,有效优先级最高,中奖几率最高,最可能执行,当thread1执行完成之后,thread3的优先级最高,中奖几率最高,最可能执行,thread2优先级最低。