Lottery Scheduling
Lottery scheduling hands each process a number of tickets and draws one at random every quantum. The winner runs, so over time each process gets CPU in proportion to the tickets it holds.
Tickets as Shares of the CPU
- Assign tickets – give each process tickets in proportion to the CPU share it should get.
- Draw – at the end of each quantum, pick a random number from 0 to total tickets − 1.
- Find the winner – walk the process list, adding up tickets, until the running total exceeds the number.
- Run – the winner gets the CPU for one quantum; then hold the next lottery.
Lottery scheduling is a form of proportional share scheduling, introduced by Carl Waldspurger and William Weihl in 1994. Every process holds some number of lottery tickets. At each scheduling decision the scheduler draws a random ticket, and the process holding it runs for the next time quantum.
The idea is that tickets represent a share of the CPU, not a priority. A process with 50 of 100 tickets wins half the lotteries on average, so it receives about half the CPU time; a process with 10 tickets receives about a tenth. Changing a process's share is as simple as changing its ticket count.
- Type: randomized, proportional-share scheduling
- Preemptive: a new lottery is held every quantum
- Share of process i = tᵢ / T, where T is the total number of tickets
- No history is kept: every draw is independent
Drawing the Winner
The processes are kept in a list with their ticket counts. To hold a lottery, the scheduler picks a random winner w with 0 ≤ w < T, then walks the list keeping a running total of tickets. The first process whose running total is greater than w is the winner. This is exactly what the listing further down does in holdLottery.
The diagram shows one draw. With A = 50, B = 30 and C = 20, the ranges are A 0–49, B 50–79 and C 80–99. For w = 63 the running total is 50 after A (not greater than 63) and 80 after B (greater), so B runs. Sorting the list with the largest ticket holders first makes the average walk shorter; for many processes a tree of partial sums finds the winner in O(log n).
- Winner selection: O(n) list walk, or O(log n) with a tree of ticket sums
- Adding or removing a process just changes T; nothing else is recomputed
- A new process is competitive immediately, in proportion to its tickets
Fairness, Starvation, and Response Time
The scheme is fair in expectation. If a process holds a fraction p = t / T of the tickets, the number of lotteries it wins out of n is binomially distributed: the expected number of wins is n·p and the variance is n·p·(1 − p). The relative error therefore shrinks like 1 / √n: over a few quanta shares can be far off, over thousands they are close.
There is no starvation. A process with even one ticket has a non-zero chance of winning every draw, so it will eventually run. The number of lotteries until its first win is geometrically distributed with mean 1 / p: a process holding 20% of the tickets waits 5 quanta on average.
- Win probability – p = t / T; C with 20 of 100 tickets has p = 0.2
- Expected wins in n draws – n · p; C expects 200 of 1000
- Variance – n · p · (1 − p) = 160 for C, a standard deviation of about 12.6 wins
- Wait for the first win – 1 / p draws on average, 5 quanta for C
- Edge case – a process with zero tickets never runs; one ticket is enough to avoid starvation
Terms, operations, and practical uses
Core vocabulary
- TicketA unit of CPU entitlement; share = tickets held / total tickets.
- Proportional shareScheduling that divides the CPU in given ratios rather than by priority.
- Winning ticketA random number below the total; its owner runs the next quantum.
- Stride schedulingThe deterministic version: run the lowest pass, then add its stride.
Formulas
- Win probabilityp = t / T for a process with t of T tickets
- Expected winsn · p over n lotteries, variance n · p · (1 − p)
- Expected wait1 / p quanta until the first win
- Stridestride = L / t for a large constant L; pass += stride after each run
Related lessons
- CPU Scheduling AlgorithmsThe deterministic schedulers this one is compared with.
- Completely Fair Scheduler (CFS)Linux's weighted fair scheduler, a descendant of stride scheduling.
- Priority SchedulingAbsolute importance instead of a share, and the starvation it causes.
- Round Robin SchedulingEqual quanta in a fixed order: the deterministic equal-share case.
Three processes, eleven draws, one ticket transfer
class Random:
# A fixed linear congruential generator, so every run draws the same tickets.
def __init__(self, seed):
self.state = seed
def below(self, n):
self.state = (self.state * 1103515245 + 12345) % 2**31
return (self.state >> 16) % n
def hold_lottery(procs, rng):
# procs: list of (name, tickets). Walk the list until the running total passes the winner.
total = sum(tickets for _, tickets in procs)
winner = rng.below(total)
counter = 0
for name, tickets in procs:
counter += tickets
if counter > winner:
return winner, name
rng = Random(3)
procs = [("A", 50), ("B", 30), ("C", 20)]
wins = {name: 0 for name, _ in procs}
for q in range(1, 9):
ticket, name = hold_lottery(procs, rng)
wins[name] += 1
print(f"quantum {q}: ticket {ticket:>2} -> {name}")
print("wins after 8:", " ".join(f"{n}={w}" for n, w in wins.items()))
# B blocks waiting for server C and lends it all 30 tickets.
lent = [("A", 50), ("C", 20 + 30)]
for q in range(9, 12):
ticket, name = hold_lottery(lent, rng)
print(f"quantum {q}: ticket {ticket:>2} -> {name} (B's tickets lent to C)")
wins = {name: 0 for name, _ in procs}
for _ in range(1000):
wins[hold_lottery(procs, rng)[1]] += 1
for name, tickets in procs:
print(f"{name}: {tickets} tickets, won {wins[name]} of 1000 = {wins[name] / 10:.1f}%")#include <cstdint>
#include <cstdio>
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace std;
// A fixed linear congruential generator, so every run draws the same tickets.
struct Random {
uint64_t state;
int below(int n) {
state = (state * 1103515245 + 12345) % 2147483648ULL;
return (state >> 16) % n;
}
};
using Procs = vector<pair<string, int>>;
// Walk the list until the running total passes the winning ticket.
pair<int, string> holdLottery(const Procs& procs, Random& rng) {
int total = 0;
for (const auto& [name, tickets] : procs) total += tickets;
int winner = rng.below(total);
int counter = 0;
for (const auto& [name, tickets] : procs) {
counter += tickets;
if (counter > winner) return {winner, name};
}
return {winner, ""}; // unreachable: winner < total
}
int main() {
Random rng{3};
Procs procs = {{"A", 50}, {"B", 30}, {"C", 20}};
map<string, int> wins;
for (int q = 1; q <= 8; q++) {
auto [ticket, name] = holdLottery(procs, rng);
wins[name]++;
printf("quantum %d: ticket %2d -> %s\n", q, ticket, name.c_str());
}
printf("wins after 8: A=%d B=%d C=%d\n", wins["A"], wins["B"], wins["C"]);
// B blocks waiting for server C and lends it all 30 tickets.
Procs lent = {{"A", 50}, {"C", 20 + 30}};
for (int q = 9; q <= 11; q++) {
auto [ticket, name] = holdLottery(lent, rng);
printf("quantum %d: ticket %2d -> %s (B's tickets lent to C)\n", q, ticket, name.c_str());
}
wins.clear();
for (int i = 0; i < 1000; i++) wins[holdLottery(procs, rng).second]++;
for (const auto& [name, tickets] : procs) {
printf("%s: %d tickets, won %d of 1000 = %.1f%%\n", name.c_str(), tickets, wins[name], wins[name] / 10.0);
}
return 0;
}import java.util.LinkedHashMap;
import java.util.Map;
public class Main {
// A fixed linear congruential generator, so every run draws the same tickets.
static class Random {
long state;
Random(long seed) {
state = seed;
}
int below(int n) {
state = (state * 1103515245L + 12345) % 2147483648L;
return (int) ((state >> 16) % n);
}
}
record Proc(String name, int tickets) {}
record Draw(int ticket, String name) {}
// Walk the list until the running total passes the winning ticket.
static Draw holdLottery(Proc[] procs, Random rng) {
int total = 0;
for (Proc p : procs) total += p.tickets();
int winner = rng.below(total);
int counter = 0;
for (Proc p : procs) {
counter += p.tickets();
if (counter > winner) return new Draw(winner, p.name());
}
throw new IllegalStateException("winner must be below total");
}
public static void main(String[] args) {
Random rng = new Random(3);
Proc[] procs = {new Proc("A", 50), new Proc("B", 30), new Proc("C", 20)};
Map<String, Integer> wins = new LinkedHashMap<>();
for (Proc p : procs) wins.put(p.name(), 0);
for (int q = 1; q <= 8; q++) {
Draw d = holdLottery(procs, rng);
wins.merge(d.name(), 1, Integer::sum);
System.out.printf("quantum %d: ticket %2d -> %s%n", q, d.ticket(), d.name());
}
System.out.printf("wins after 8: A=%d B=%d C=%d%n", wins.get("A"), wins.get("B"), wins.get("C"));
// B blocks waiting for server C and lends it all 30 tickets.
Proc[] lent = {new Proc("A", 50), new Proc("C", 20 + 30)};
for (int q = 9; q <= 11; q++) {
Draw d = holdLottery(lent, rng);
System.out.printf("quantum %d: ticket %2d -> %s (B's tickets lent to C)%n", q, d.ticket(), d.name());
}
for (Proc p : procs) wins.put(p.name(), 0);
for (int i = 0; i < 1000; i++) wins.merge(holdLottery(procs, rng).name(), 1, Integer::sum);
for (Proc p : procs) {
int w = wins.get(p.name());
System.out.printf("%s: %d tickets, won %d of 1000 = %.1f%%%n", p.name(), p.tickets(), w, w / 10.0);
}
}
}Step through it
Running on A 50 tickets, B 30, C 20; 8 draws, B lends its tickets to C for 3 draws, then 1000 draws
Ticket Transfer, Inflation, Currencies, and Compensation
Tickets are an abstract, movable resource, and that is what makes the scheme flexible. Four mechanisms from the original design let the system adjust shares without touching the scheduler itself.
Ticket transfer is what the tracer shows: when a client blocks waiting for a server, it lends its tickets to the server, so the server works on the client's request with the client's share. This also avoids priority inversion, because a low-share server is boosted by exactly the share of whoever is waiting on it.
- Ticket transfer – a blocked process hands its tickets to the one it waits on; the shares of everyone else are untouched
- Ticket inflation – a process mints more tickets for itself; safe only among processes that trust each other
- Ticket currency – a user or group gets its own currency backed by base tickets, so inflation inside the group cannot affect other groups
- Compensation tickets – a process that used only a fraction f of its quantum has its tickets inflated by 1 / f until it next runs, so I/O-bound processes that block early still get their fair share
Preemption and Blocked Processes
Lottery scheduling is preemptive. A lottery is held every time quantum, and the process that was running can lose the next draw to any other ready process. In that sense it behaves like Round Robin with a random choice instead of a queue: the quantum bounds how long any process can hold the CPU, and a timer interrupt triggers the next draw.
A blocked process takes no part in lotteries while it waits. Its tickets are either inactive or, with ticket transfer, lent to the process it is waiting for.
- Preemptive: one lottery per quantum, triggered by the timer
- Only ready processes are in the draw
- Compare Round Robin: equal turns in a fixed order
Lottery vs Stride Scheduling
Randomness is simple, but it makes short-run shares noisy. Stride scheduling, by the same authors, gives the same proportions deterministically. Each process has a stride equal to a large constant divided by its tickets, and a pass value that starts at 0. The scheduler always runs the process with the lowest pass, then adds its stride to its pass.
With A = 50, B = 30 and C = 20 tickets and a constant of 600, the strides are 12, 20 and 30. A process with more tickets takes smaller steps, so it is chosen more often, exactly in proportion. The same idea, running whoever is furthest behind, is the basis of Linux's Completely Fair Scheduler.
| Aspect | Lottery | Stride |
|---|---|---|
| Choice each quantum | random ticket | lowest pass value |
| Short-run accuracy | noisy; error ∝ √n | exact within one quantum |
| State per process | ticket count only | tickets, stride and pass |
| New process joining | trivial: add its tickets | must set its pass to avoid a head start or a penalty |
| Global state | none | pass values must be kept consistent |
- Lottery: stateless and simple, fair on average
- Stride: deterministic and precise, more bookkeeping
- CFS's virtual runtime is a stride-like pass value
Strengths, Limits and Where It Is Used
It is rarely the default CPU scheduler of a general-purpose OS, but its ideas are used wherever a resource must be divided in given proportions: CPU shares for virtual machines and containers, network bandwidth, and even mutex acquisition, where waiting threads draw lots for the lock.
Its strengths are simplicity and control: shares are set directly by ticket counts, almost no state is kept, and processes can join or leave at any time. Its limits come from the randomness and from the policy question it leaves open.
- Limit: short runs – shares are only correct on average, so there is no response-time guarantee for real-time tasks
- Limit: choosing tickets – the algorithm divides the CPU fairly but cannot say how many tickets each process deserves
- Limit: reproducibility – random draws make benchmarks and bugs harder to repeat
- Used in – hypervisor CPU shares for virtual machines, cgroup CPU weights, memory and I/O bandwidth sharing
- Compare priority scheduling, where importance is absolute, not a share