Patternadvanced
Scheduler
Also called scheduler pattern, scheduler, access scheduler, scheduling policy object.
A scheduler object decides which waiting thread uses a shared resource next. Threads call enter and done, and one policy, such as priority or first come first served, sets the order.
- Family
- concurrency
- Intent
- Control the order in which threads that wait for a shared resource get it, and keep the ordering policy in one object, separate from the threads and from the resource.
- Also called
- Scheduling policy
Intent
Scheduling deals with the problem of deciding which of the outstanding requests is to be allocated resources.1 The Scheduler pattern puts that decision in one object. Threads ask the scheduler for a shared resource, and the scheduler decides which waiting thread gets it next.
Problem
Several threads wait for one resource, for example a printer. A plain lock does not say which waiting thread gets the resource when it becomes free. In Python, when more than one thread is blocked in acquire(), only one thread proceeds when a release() call unlocks the lock, and which one of the waiting threads proceeds is not defined, and may vary across implementations.2 A Java ReentrantLock without its fairness setting does not guarantee any particular access order.3
Some programs need an order: urgent jobs first, or each job in its turn. A lock alone cannot give that order, and code that sorts the threads in each caller is hard to change.
Solution
Put a scheduler object between the threads and the resource. A thread calls enter before it uses the resource and done after it. If the resource is free and nobody waits, enter returns at once. If not, the scheduler adds the thread to its waiting list and the thread sleeps. When the thread that holds the resource calls done, the scheduler applies its policy to the waiting list, chooses one thread, and wakes it. The resource stays busy and passes directly to the chosen thread, so no other thread can take it in between.
job threads scheduler printer
report(2) ── enter ──► waiting: report, invoice,
invoice(1) ─ enter ──► photo, label
photo(3) ─── enter ──► │
label(1) ─── enter ──► │
first ────── done ───► policy: lowest number, then first to arrive
└─► wake invoice ─────────────► invoice
invoice ──── done ───► └─► wake label ───────────────► label
The policy is the only part that knows the order. In the Active Object pattern, one of the elements is a scheduler, which decides which request to execute next.4
Example
The first job holds the printer. Four jobs then arrive in a known order: report with priority 2, invoice with priority 1, photo with priority 3 and label with priority 1. The policy takes the lowest priority number first, and the first to arrive among jobs with the same priority. Invoice and label share priority 1, so invoice prints before label because it arrived first. Only one job uses the printer at a time.
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
The examples for each language show the same program.
import threading
class Scheduler:
"""Decides which waiting thread uses the printer next."""
def __init__(self):
self._cond = threading.Condition()
self._busy = False
self._waiting = [] # entries (priority, arrival, name)
self._arrivals = 0
self._chosen = None
def enter(self, name, priority):
with self._cond:
if not self._busy and not self._waiting:
self._busy = True
return
self._arrivals += 1
entry = (priority, self._arrivals, name)
self._waiting.append(entry)
self._cond.notify_all()
# Sleep until the scheduler chooses this thread.
self._cond.wait_for(lambda: self._chosen == entry)
self._chosen = None
def done(self):
with self._cond:
if not self._waiting:
self._busy = False
return
# The policy: the lowest priority number first, then the first to arrive.
entry = min(self._waiting)
self._waiting.remove(entry)
self._chosen = entry # the printer stays busy and passes to that thread
self._cond.notify_all()
def wait_until_waiting(self, n):
with self._cond:
self._cond.wait_for(lambda: len(self._waiting) >= n, timeout=5)
return len(self._waiting)
scheduler = Scheduler()
lock = threading.Lock()
order = []
on_printer = 0
most_on_printer = 0
def use_printer(name):
global on_printer, most_on_printer
with lock:
on_printer += 1
most_on_printer = max(most_on_printer, on_printer)
order.append(name)
with lock:
on_printer -= 1
def print_job(name, priority):
scheduler.enter(name, priority)
use_printer(name)
scheduler.done()
scheduler.enter("first", 0) # the first job takes the free printer
use_printer("first")
jobs = [("report", 2), ("invoice", 1), ("photo", 3), ("label", 1)]
threads = []
for n, (name, priority) in enumerate(jobs, start=1):
t = threading.Thread(target=print_job, args=(name, priority))
t.start()
threads.append(t)
scheduler.wait_until_waiting(n) # start the jobs in a known order
print("jobs waiting when the first job ends:", scheduler.wait_until_waiting(len(jobs)))
scheduler.done()
for t in threads:
t.join()
print("print order:", ", ".join(order))
print("jobs on the printer at once, at most:", most_on_printer)
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. A class with a
threading.Condition;enterwaits withwait_foruntildonechooses its entry withmin.
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <tuple>
#include <vector>
// Decides which waiting thread uses the printer next.
class Scheduler {
public:
void enter(const std::string& name, int priority) {
std::unique_lock<std::mutex> lock(m_);
if (!busy_ && waiting_.empty()) {
busy_ = true;
return;
}
Entry entry{priority, ++arrivals_, name};
waiting_.push_back(entry);
cv_.notify_all();
// Sleep until the scheduler chooses this thread.
cv_.wait(lock, [&] { return chosen_ == entry.arrival; });
chosen_ = 0;
}
void done() {
std::lock_guard<std::mutex> lock(m_);
if (waiting_.empty()) {
busy_ = false;
return;
}
// The policy: the lowest priority number first, then the first to arrive.
auto it = std::min_element(waiting_.begin(), waiting_.end(), [](const Entry& a, const Entry& b) {
return std::tie(a.priority, a.arrival) < std::tie(b.priority, b.arrival);
});
chosen_ = it->arrival; // the printer stays busy and passes to that thread
waiting_.erase(it);
cv_.notify_all();
}
size_t wait_until_waiting(size_t n) {
std::unique_lock<std::mutex> lock(m_);
cv_.wait_for(lock, std::chrono::seconds(5), [&] { return waiting_.size() >= n; });
return waiting_.size();
}
private:
struct Entry {
int priority;
int arrival;
std::string name;
};
std::mutex m_;
std::condition_variable cv_;
bool busy_ = false;
std::vector<Entry> waiting_;
int arrivals_ = 0;
int chosen_ = 0; // the arrival number of the chosen entry
};
Scheduler scheduler;
std::mutex order_m;
std::vector<std::string> order;
std::atomic<int> on_printer{0};
int most_on_printer = 0;
void use_printer(const std::string& name) {
int now = ++on_printer;
{
std::lock_guard<std::mutex> lock(order_m);
most_on_printer = std::max(most_on_printer, now);
order.push_back(name);
}
--on_printer;
}
int main() {
scheduler.enter("first", 0); // the first job takes the free printer
use_printer("first");
std::vector<std::pair<std::string, int>> jobs = {{"report", 2}, {"invoice", 1}, {"photo", 3}, {"label", 1}};
std::vector<std::thread> threads;
for (size_t i = 0; i < jobs.size(); i++) {
auto job = jobs[i];
threads.emplace_back([job] {
scheduler.enter(job.first, job.second);
use_printer(job.first);
scheduler.done();
});
scheduler.wait_until_waiting(i + 1); // start the jobs in a known order
}
std::cout << "jobs waiting when the first job ends: " << scheduler.wait_until_waiting(jobs.size()) << "\n";
scheduler.done();
for (auto& t : threads) t.join();
std::cout << "print order: ";
for (size_t i = 0; i < order.size(); i++) std::cout << (i ? ", " : "") << order[i];
std::cout << "\n";
std::cout << "jobs on the printer at once, at most: " << most_on_printer << "\n";
}
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. A class with
std::mutexandstd::condition_variable;enterwaits with a predicate untildonechooses its arrival number.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
record Entry(int priority, int arrival, String name) {}
// Decides which waiting thread uses the printer next.
static class Scheduler {
private boolean busy = false;
private final List<Entry> waiting = new ArrayList<>();
private int arrivals = 0;
private Entry chosen = null;
synchronized void enter(String name, int priority) throws InterruptedException {
if (!busy && waiting.isEmpty()) {
busy = true;
return;
}
Entry entry = new Entry(priority, ++arrivals, name);
waiting.add(entry);
notifyAll();
// Sleep until the scheduler chooses this thread.
while (chosen != entry) wait();
chosen = null;
}
synchronized void done() {
if (waiting.isEmpty()) {
busy = false;
return;
}
// The policy: the lowest priority number first, then the first to arrive.
Entry entry = waiting.stream()
.min(Comparator.comparingInt(Entry::priority).thenComparingInt(Entry::arrival))
.get();
waiting.remove(entry);
chosen = entry; // the printer stays busy and passes to that thread
notifyAll();
}
synchronized int waitUntilWaiting(int n) throws InterruptedException {
long end = System.currentTimeMillis() + 5000;
while (waiting.size() < n && System.currentTimeMillis() < end) wait(100);
return waiting.size();
}
}
static final Scheduler scheduler = new Scheduler();
static final List<String> order = Collections.synchronizedList(new ArrayList<>());
static final AtomicInteger onPrinter = new AtomicInteger();
static final AtomicInteger mostOnPrinter = new AtomicInteger();
static void usePrinter(String name) {
mostOnPrinter.accumulateAndGet(onPrinter.incrementAndGet(), Math::max);
order.add(name);
onPrinter.decrementAndGet();
}
public static void main(String[] args) throws Exception {
scheduler.enter("first", 0); // the first job takes the free printer
usePrinter("first");
String[] names = {"report", "invoice", "photo", "label"};
int[] priorities = {2, 1, 3, 1};
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < names.length; i++) {
String name = names[i];
int priority = priorities[i];
Thread t = new Thread(() -> {
try {
scheduler.enter(name, priority);
usePrinter(name);
scheduler.done();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
t.start();
threads.add(t);
scheduler.waitUntilWaiting(i + 1); // start the jobs in a known order
}
System.out.println("jobs waiting when the first job ends: " + scheduler.waitUntilWaiting(names.length));
scheduler.done();
for (Thread t : threads) t.join();
System.out.println("print order: " + String.join(", ", order));
System.out.println("jobs on the printer at once, at most: " + mostOnPrinter.get());
}
}
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. A class with
synchronizedmethods,wait()in awhileloop andnotifyAll(). AReentrantLockorSemaphorein fair mode gives only the FIFO policy.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
// Decides which waiting thread uses the printer next.
class Scheduler
{
record Entry(int Priority, int Arrival, string Name);
readonly object gate = new object();
bool busy = false;
readonly List<Entry> waiting = new List<Entry>();
int arrivals = 0;
Entry chosen = null;
public void Enter(string name, int priority)
{
lock (gate)
{
if (!busy && waiting.Count == 0)
{
busy = true;
return;
}
var entry = new Entry(priority, ++arrivals, name);
waiting.Add(entry);
Monitor.PulseAll(gate);
// Sleep until the scheduler chooses this thread.
while (!ReferenceEquals(chosen, entry)) Monitor.Wait(gate);
chosen = null;
}
}
public void Done()
{
lock (gate)
{
if (waiting.Count == 0)
{
busy = false;
return;
}
// The policy: the lowest priority number first, then the first to arrive.
var entry = waiting.OrderBy(e => e.Priority).ThenBy(e => e.Arrival).First();
waiting.Remove(entry);
chosen = entry; // the printer stays busy and passes to that thread
Monitor.PulseAll(gate);
}
}
public int WaitUntilWaiting(int n)
{
lock (gate)
{
var end = DateTime.UtcNow.AddSeconds(5);
while (waiting.Count < n && DateTime.UtcNow < end) Monitor.Wait(gate, 100);
return waiting.Count;
}
}
}
class Program
{
static readonly Scheduler scheduler = new Scheduler();
static readonly List<string> order = new List<string>();
static int onPrinter = 0, mostOnPrinter = 0;
static void UsePrinter(string name)
{
int now = Interlocked.Increment(ref onPrinter);
lock (order)
{
mostOnPrinter = Math.Max(mostOnPrinter, now);
order.Add(name);
}
Interlocked.Decrement(ref onPrinter);
}
static void Main()
{
scheduler.Enter("first", 0); // the first job takes the free printer
UsePrinter("first");
var jobs = new (string Name, int Priority)[] { ("report", 2), ("invoice", 1), ("photo", 3), ("label", 1) };
var threads = new List<Thread>();
for (int i = 0; i < jobs.Length; i++)
{
var job = jobs[i];
var t = new Thread(() =>
{
scheduler.Enter(job.Name, job.Priority);
UsePrinter(job.Name);
scheduler.Done();
});
t.Start();
threads.Add(t);
scheduler.WaitUntilWaiting(i + 1); // start the jobs in a known order
}
Console.WriteLine("jobs waiting when the first job ends: " + scheduler.WaitUntilWaiting(jobs.Length));
scheduler.Done();
foreach (var t in threads) t.Join();
Console.WriteLine("print order: " + string.Join(", ", order));
Console.WriteLine("jobs on the printer at once, at most: " + mostOnPrinter);
}
}
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. A class with
lock,Monitor.Waitin awhileloop andMonitor.PulseAll.
// Decides which waiting task uses the printer next.
class Scheduler {
constructor() {
this.busy = false;
this.waiting = []; // entries { priority, arrival, name, wake }
this.arrivals = 0;
}
enter(name, priority) {
if (!this.busy && this.waiting.length === 0) {
this.busy = true;
return Promise.resolve();
}
// The task sleeps until the scheduler chooses it.
return new Promise((wake) => {
this.waiting.push({ priority, arrival: ++this.arrivals, name, wake });
});
}
done() {
if (this.waiting.length === 0) {
this.busy = false;
return;
}
// The policy: the lowest priority number first, then the first to arrive.
let best = 0;
this.waiting.forEach((e, i) => {
const b = this.waiting[best];
if (e.priority < b.priority || (e.priority === b.priority && e.arrival < b.arrival)) best = i;
});
const [entry] = this.waiting.splice(best, 1);
entry.wake(); // the printer stays busy and passes to that task
}
}
const scheduler = new Scheduler();
const order = [];
let onPrinter = 0;
let mostOnPrinter = 0;
async function usePrinter(name) {
onPrinter++;
mostOnPrinter = Math.max(mostOnPrinter, onPrinter);
order.push(name);
await null; // let other tasks run while the job prints
onPrinter--;
}
async function printJob(name, priority) {
await scheduler.enter(name, priority);
await usePrinter(name);
scheduler.done();
}
async function main() {
await scheduler.enter("first", 0); // the first job takes the free printer
await usePrinter("first");
const jobs = [["report", 2], ["invoice", 1], ["photo", 3], ["label", 1]];
// Each call puts the job in the waiting list before it returns, in this order.
const tasks = jobs.map(([name, priority]) => printJob(name, priority));
console.log("jobs waiting when the first job ends:", scheduler.waiting.length);
scheduler.done();
await Promise.all(tasks);
console.log("print order:", order.join(", "));
console.log("jobs on the printer at once, at most:", mostOnPrinter);
}
main();
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. The tasks share one thread.
enterreturns a promise and keeps itsresolvefunction in the waiting list, anddoneresolves the chosen one.
interface Entry {
priority: number;
arrival: number;
name: string;
wake: () => void;
}
// Decides which waiting task uses the printer next.
class Scheduler {
busy: boolean;
waiting: Entry[];
arrivals: number;
constructor() {
this.busy = false;
this.waiting = []; // entries { priority, arrival, name, wake }
this.arrivals = 0;
}
enter(name: string, priority: number): Promise<void> {
if (!this.busy && this.waiting.length === 0) {
this.busy = true;
return Promise.resolve();
}
// The task sleeps until the scheduler chooses it.
return new Promise<void>((wake) => {
this.waiting.push({ priority, arrival: ++this.arrivals, name, wake });
});
}
done(): void {
if (this.waiting.length === 0) {
this.busy = false;
return;
}
// The policy: the lowest priority number first, then the first to arrive.
let best = 0;
this.waiting.forEach((e, i) => {
const b = this.waiting[best];
if (e.priority < b.priority || (e.priority === b.priority && e.arrival < b.arrival)) best = i;
});
const [entry] = this.waiting.splice(best, 1);
entry.wake(); // the printer stays busy and passes to that task
}
}
const scheduler = new Scheduler();
const order: string[] = [];
let onPrinter = 0;
let mostOnPrinter = 0;
async function usePrinter(name: string): Promise<void> {
onPrinter++;
mostOnPrinter = Math.max(mostOnPrinter, onPrinter);
order.push(name);
await null; // let other tasks run while the job prints
onPrinter--;
}
async function printJob(name: string, priority: number): Promise<void> {
await scheduler.enter(name, priority);
await usePrinter(name);
scheduler.done();
}
async function main(): Promise<void> {
await scheduler.enter("first", 0); // the first job takes the free printer
await usePrinter("first");
const jobs: [string, number][] = [["report", 2], ["invoice", 1], ["photo", 3], ["label", 1]];
// Each call puts the job in the waiting list before it returns, in this order.
const tasks = jobs.map(([name, priority]) => printJob(name, priority));
console.log("jobs waiting when the first job ends:", scheduler.waiting.length);
scheduler.done();
await Promise.all(tasks);
console.log("print order:", order.join(", "));
console.log("jobs on the printer at once, at most:", mostOnPrinter);
}
main();
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. The tasks share one thread.
enterreturns aPromise<void>and keeps itsresolvefunction in the waiting list, anddoneresolves the chosen one.
package main
import (
"fmt"
"strings"
"sync"
"sync/atomic"
"time"
)
type entry struct {
priority, arrival int
name string
}
// Scheduler decides which waiting goroutine uses the printer next.
type Scheduler struct {
mu sync.Mutex
cond *sync.Cond
busy bool
waiting []entry
arrivals int
chosen int // the arrival number of the chosen entry
}
func NewScheduler() *Scheduler {
s := &Scheduler{}
s.cond = sync.NewCond(&s.mu)
return s
}
func (s *Scheduler) Enter(name string, priority int) {
s.mu.Lock()
defer s.mu.Unlock()
if !s.busy && len(s.waiting) == 0 {
s.busy = true
return
}
s.arrivals++
e := entry{priority, s.arrivals, name}
s.waiting = append(s.waiting, e)
s.cond.Broadcast()
// Sleep until the scheduler chooses this goroutine.
for s.chosen != e.arrival {
s.cond.Wait()
}
s.chosen = 0
}
func (s *Scheduler) Done() {
s.mu.Lock()
defer s.mu.Unlock()
if len(s.waiting) == 0 {
s.busy = false
return
}
// The policy: the lowest priority number first, then the first to arrive.
best := 0
for i, e := range s.waiting {
b := s.waiting[best]
if e.priority < b.priority || (e.priority == b.priority && e.arrival < b.arrival) {
best = i
}
}
s.chosen = s.waiting[best].arrival // the printer stays busy and passes to that goroutine
s.waiting = append(s.waiting[:best], s.waiting[best+1:]...)
s.cond.Broadcast()
}
func (s *Scheduler) WaitUntilWaiting(n int) int {
deadline := time.Now().Add(5 * time.Second)
for {
s.mu.Lock()
got := len(s.waiting)
s.mu.Unlock()
if got >= n || time.Now().After(deadline) {
return got
}
time.Sleep(time.Millisecond)
}
}
var (
scheduler = NewScheduler()
orderMu sync.Mutex
order []string
onPrinter atomic.Int32
mostOnPrinter int32
)
func usePrinter(name string) {
now := onPrinter.Add(1)
orderMu.Lock()
mostOnPrinter = max(mostOnPrinter, now)
order = append(order, name)
orderMu.Unlock()
onPrinter.Add(-1)
}
func main() {
scheduler.Enter("first", 0) // the first job takes the free printer
usePrinter("first")
jobs := []struct {
name string
priority int
}{{"report", 2}, {"invoice", 1}, {"photo", 3}, {"label", 1}}
var wg sync.WaitGroup
for i, job := range jobs {
wg.Add(1)
go func() {
defer wg.Done()
scheduler.Enter(job.name, job.priority)
usePrinter(job.name)
scheduler.Done()
}()
scheduler.WaitUntilWaiting(i + 1) // start the jobs in a known order
}
fmt.Println("jobs waiting when the first job ends:", scheduler.WaitUntilWaiting(len(jobs)))
scheduler.Done()
wg.Wait()
fmt.Println("print order:", strings.Join(order, ", "))
fmt.Println("jobs on the printer at once, at most:", mostOnPrinter)
}
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. A type with
sync.Mutexandsync.Cond;EntercallsWaitin aforloop untilDonechooses its arrival number.
use std::sync::atomic::{AtomicI32, Ordering};
use std::sync::{Condvar, Mutex};
use std::thread;
use std::time::Duration;
struct State {
busy: bool,
waiting: Vec<(i32, i32, String)>, // entries (priority, arrival, name)
arrivals: i32,
chosen: i32, // the arrival number of the chosen entry
}
// Decides which waiting thread uses the printer next.
struct Scheduler {
state: Mutex<State>,
cond: Condvar,
}
impl Scheduler {
fn new() -> Self {
Scheduler {
state: Mutex::new(State { busy: false, waiting: Vec::new(), arrivals: 0, chosen: 0 }),
cond: Condvar::new(),
}
}
fn enter(&self, name: &str, priority: i32) {
let mut s = self.state.lock().unwrap();
if !s.busy && s.waiting.is_empty() {
s.busy = true;
return;
}
s.arrivals += 1;
let arrival = s.arrivals;
s.waiting.push((priority, arrival, name.to_string()));
self.cond.notify_all();
// Sleep until the scheduler chooses this thread.
let mut s = self.cond.wait_while(s, |s| s.chosen != arrival).unwrap();
s.chosen = 0;
}
fn done(&self) {
let mut s = self.state.lock().unwrap();
if s.waiting.is_empty() {
s.busy = false;
return;
}
// The policy: the lowest priority number first, then the first to arrive.
let best = (0..s.waiting.len()).min_by_key(|&i| (s.waiting[i].0, s.waiting[i].1)).unwrap();
let entry = s.waiting.remove(best);
s.chosen = entry.1; // the printer stays busy and passes to that thread
self.cond.notify_all();
}
fn wait_until_waiting(&self, n: usize) -> usize {
let s = self.state.lock().unwrap();
let (s, _) = self.cond.wait_timeout_while(s, Duration::from_secs(5), |s| s.waiting.len() < n).unwrap();
s.waiting.len()
}
}
static ON_PRINTER: AtomicI32 = AtomicI32::new(0);
static ORDER: Mutex<(Vec<String>, i32)> = Mutex::new((Vec::new(), 0)); // (order, most on printer)
fn use_printer(name: &str) {
let now = ON_PRINTER.fetch_add(1, Ordering::SeqCst) + 1;
{
let mut o = ORDER.lock().unwrap();
o.1 = o.1.max(now);
o.0.push(name.to_string());
}
ON_PRINTER.fetch_sub(1, Ordering::SeqCst);
}
fn main() {
let scheduler = Scheduler::new();
scheduler.enter("first", 0); // the first job takes the free printer
use_printer("first");
let jobs = [("report", 2), ("invoice", 1), ("photo", 3), ("label", 1)];
thread::scope(|scope| {
for (i, &(name, priority)) in jobs.iter().enumerate() {
let scheduler = &scheduler;
scope.spawn(move || {
scheduler.enter(name, priority);
use_printer(name);
scheduler.done();
});
scheduler.wait_until_waiting(i + 1); // start the jobs in a known order
}
println!("jobs waiting when the first job ends: {}", scheduler.wait_until_waiting(jobs.len()));
scheduler.done();
});
let o = ORDER.lock().unwrap();
println!("print order: {}", o.0.join(", "));
println!("jobs on the printer at once, at most: {}", o.1);
}
jobs waiting when the first job ends: 4
print order: first, invoice, label, report, photo
jobs on the printer at once, at most: 1
- Verdict: idiom. A struct with
MutexandCondvar;enteruseswait_whileuntildonechooses its arrival number.
Consequences
Benefits:
- The order is set in one place. A different policy changes the order for every thread, and the threads do not change. The policy can be a strategy object.
- The scheduler can give a guarantee that a plain lock does not give. With first in, first out, there is no starvation, because each process gets a chance to be executed after a definite time.1
- The main purposes of scheduling algorithms are to minimize resource starvation and to ensure fairness amongst the parties utilizing the resources.1 A scheduler object lets a program choose its own balance of these goals.
Liabilities:
- A policy can starve a thread. With fixed priorities, processes in lower-priority queues are selected only when all of the higher-priority queues are empty.1
- Fairness costs speed. Programs using fair locks accessed by many threads may display lower overall throughput than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation.3
- The scheduler controls only access to the resource. Fairness of locks does not guarantee fairness of thread scheduling.3
- Every thread must call
done. A thread that fails beforedonekeeps the resource busy, and every waiting thread sleeps forever.
This program applies a strict priority policy. One photo job waits with priority 3, and each time a job ends, a new invoice job with priority 1 arrives:
This code runs but gives a wrong answer on purpose.
# A strict priority policy. Each time a job ends, a new urgent job arrives.
waiting = [(1, "invoice 1"), (3, "photo")]
run = []
for n in range(2, 12):
job = min(waiting) # always the lowest priority number
waiting.remove(job)
run.append(job[1])
waiting.append((1, f"invoice {n}")) # a new urgent job arrives
print("jobs run:", len(run))
print("photo job run:", "photo" in run)
print("jobs still waiting:", [name for _, name in sorted(waiting)])
jobs run: 10
photo job run: False
jobs still waiting: ['invoice 11', 'photo']
The photo job never runs while urgent jobs keep arriving. Add a limit to the wait, raise the priority of a job that waits long, or use first in, first out.
When not to use it
Do not use a scheduler when the order does not matter. A plain lock is simpler and does not keep a waiting list. If the policy that you need is first in, first out, a fair lock or semaphore from the library can be enough: a Java Semaphore with fairness set to true guarantees that threads invoking any of the acquire methods are selected to obtain permits in the order in which their invocation of those methods was processed.5 If the work can wait in a queue as data instead of as sleeping threads, a priority queue in front of a thread pool can be simpler.
Variants and related patterns
- First in, first out. FIFO, also known as first come, first served (FCFS), is the simplest scheduling algorithm, and it queues processes in the order that they arrive in the ready queue.1 Its cost is that long processes can make short processes wait for a long time, which is known as the convoy effect.1 This program gives the same arrivals as the wrong program to a FIFO policy:
from collections import deque
# The same arrivals with a first-in, first-out policy.
waiting = deque(["invoice 1", "photo"])
run = []
for n in range(2, 12):
run.append(waiting.popleft()) # always the job that waited longest
waiting.append(f"invoice {n}")
print("jobs run:", len(run))
print("photo job run, as job number:", run.index("photo") + 1)
print("jobs still waiting:", list(waiting))
jobs run: 10
photo job run, as job number: 2
jobs still waiting: ['invoice 10', 'invoice 11']
- Priority levels. If the number of priority rankings is limited, fixed-priority scheduling can be characterized as a collection of FIFO queues, one for each priority ranking.1 The example uses this policy.
- Fair locks and semaphores. The library puts a FIFO scheduler inside the lock. When the fairness parameter of a Java
ReentrantLockis true, the lock favors granting access to the longest-waiting thread under contention.3 When the fairness of a JavaSemaphoreis false, barging is permitted, so a thread that callsacquire()can get a permit ahead of a thread that has been waiting.5 - Readers and writers. A read-write lock is a scheduler with a policy for two kinds of request, and its preference for readers or for writers is a scheduling decision.
Each waiting thread in enter uses guarded suspension: its guard is that the scheduler chose it. A monitor object gives the lock and the condition variable that the scheduler uses.
Known uses
- The scheduler element of the Active Object pattern.4
- Java
ReentrantLockandSemaphorein fair mode.35 - Scheduling disciplines in operating systems for threads and processes, and in disk drives and printers.1
References
- Scheduling (computing), Wikipedia, Scheduling disciplines; First come, first served; Fixed-priority pre-emptive scheduling
- threading, Thread-based parallelism, Python documentation, Lock Objects
- Java SE 21 API, java.util.concurrent.locks.ReentrantLock, the class description
- Active object, Wikipedia, lead; the list of elements
- Java SE 21 API, java.util.concurrent.Semaphore, the class description
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 1PF1PG Edit this page History Report an error Markdown