彩票调度中最不可思议的,或许就是实现简单。只需要一个不错的随机数生成器来选择中奖彩票和一个记录系统中所有进程的数据结构(一个列表),以及所有彩票的总数。
假定我们用列表记录进程。下面的例子中有A、B、C 这3 个进程,每个进程有一定数量的彩票。

原书第 67 页图示 1
在做出调度决策之前,首先要从彩票总数400 中选择一个随机数(中奖号码)1。假设选择了300。然后,遍历链表,用一个简单的计数器帮助我们找到中奖者(见图9.1)。
// counter: used to track if we've found the winner yet
int counter = 0;
// winner: use some call to a random number generator to
// get a value, between 0 and the total # of tickets
int winner = getrandom(0, totaltickets);
// current: use this to walk through the list of jobs
node_t *current = head;
// loop until the sum of ticket values is > the winner
while (current) {
counter = counter + current->tickets;
if (counter > winner)
break; // found the winner
current = current->next;
}
// 'current' is the winner: schedule it...
图9.1 彩票调度决定代码
这段代码从前向后遍历进程列表,将每张票的值加到counter 上,直到值超过winner。这时,当前的列表元素所对应的进程就是中奖者。在我们的例子中,中奖彩票是300。首先,计A 的票后,counter 增加到100。因为100 小于300,继续遍历。然后counter 会增加到150(B 的彩票),仍然小于300,继续遍历。最后,counter 增加到400(显然大于300),因此退出遍历,current 指向C(中奖者)。
要让这个过程更有效率,建议将列表项按照彩票数递减排序。这个顺序并不会影响算法的正确性,但能保证用最小的迭代次数找到需要的节点,尤其当大多数彩票被少数进程掌握时。
-
令人惊讶的是,正如Björn Lindberg 所指出的那样,要做对,这可能是一个挑战。 ↩