Programming Search⌘K

Patterncore

Guarded suspension

Also called guarded suspension, guarded wait, guarded method, wait until a condition holds.

Guarded suspension makes a method wait until it holds a lock and its precondition is true. The thread sleeps on a condition variable and checks the guard again in a loop each time it wakes up.

Family
concurrency
Intent
Run an operation only when the object is in a state that allows it, and suspend the calling thread until another thread changes the state so that the precondition holds.
Also called
Guarded wait

Intent

Guarded suspension is a software design pattern for operations that need both a lock and a precondition before they can run.1 It suspends the method call and the calling thread until the precondition, which acts as a guard, is satisfied.1

Problem

A thread calls a method on a shared object, but the object is not yet in a state that allows the operation. For example, a get method on a queue must not run when there are no items in the queue.1 The thread could poll the state in a loop, but then it uses processor time and must still take the lock each time it checks.

Solution

Take the lock and test the guard. If the guard is false, wait on a condition variable, which releases the lock while the thread sleeps. A thread that changes the state notifies the waiting threads, and each one takes the lock again and tests its guard again.1 A condition variable lets a thread block so that it consumes no CPU time while it waits for an event.2

 caller                          object (lock + condition variable)
   │ take(8)                        │
   ├──► lock ──► guard: level >= 8? │
   │             no  ──► wait ◄─────┤ (lock released while asleep)
   │                                │◄── fill(2) ──► notify all
   │             wake ──► lock ──► guard again
   │             yes ──► level -= 8 ──► unlock ──► return

Test the guard in a while loop, not in an if. In Python, the loop is necessary because wait() can return after an arbitrary long time, and the condition that caused the notify() call may no longer hold true.3 In Java, a thread can also wake up without being notified, interrupted, or timing out, a so-called spurious wakeup.4

Example

A tank starts empty. Three threads take 5, 3 and 8 units, and each one waits until the tank has enough. The main thread fills the tank with 2 units 10 times and notifies all the waiting takers after each fill. All three takers are served, the level is never negative, and 4 units are left.

units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4

The examples for each language show the same program.

PythonGitHub
import threading


class Tank:
    def __init__(self):
        self._cond = threading.Condition()
        self._level = 0
        self.lowest = 0  # the lowest level seen after a take
        self.filled = 0
        self.taken = 0
        self.served = 0

    def take(self, amount):
        with self._cond:
            # Guarded suspension: wait until the guard is true.
            self._cond.wait_for(lambda: self._level >= amount)
            self._level -= amount
            self.lowest = min(self.lowest, self._level)
            self.taken += amount
            self.served += 1

    def fill(self, amount):
        with self._cond:
            self._level += amount
            self.filled += amount
            self._cond.notify_all()  # each waiting taker checks its guard again

    def level(self):
        with self._cond:
            return self._level


tank = Tank()
amounts = [5, 3, 8]
takers = [threading.Thread(target=tank.take, args=(a,)) for a in amounts]
for t in takers:
    t.start()
for _ in range(10):
    tank.fill(2)
for t in takers:
    t.join()

print("units filled:", tank.filled)
print("units taken:", tank.taken)
print("takers served:", tank.served)
print("level never below 0:", tank.lowest >= 0)
print("units left:", tank.level())
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: stdlib. threading.Condition gives wait_for, which waits until the guard is true and tests it again after each wakeup.
#include <algorithm>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

class Tank {
public:
    int lowest = 0, filled = 0, taken = 0, served = 0;  // read after the threads end

    void take(int amount) {
        std::unique_lock<std::mutex> lock(m_);
        // Guarded suspension: wait until the guard is true.
        cv_.wait(lock, [&] { return level_ >= amount; });
        level_ -= amount;
        lowest = std::min(lowest, level_);
        taken += amount;
        served++;
    }

    void fill(int amount) {
        std::lock_guard<std::mutex> lock(m_);
        level_ += amount;
        filled += amount;
        cv_.notify_all();  // each waiting taker checks its guard again
    }

    int level() {
        std::lock_guard<std::mutex> lock(m_);
        return level_;
    }

private:
    std::mutex m_;
    std::condition_variable cv_;
    int level_ = 0;
};

int main() {
    Tank tank;
    std::vector<int> amounts = {5, 3, 8};
    std::vector<std::thread> takers;
    for (int a : amounts) takers.emplace_back([&tank, a] { tank.take(a); });
    for (int i = 0; i < 10; i++) tank.fill(2);
    for (auto& t : takers) t.join();

    std::cout << "units filled: " << tank.filled << "\n";
    std::cout << "units taken: " << tank.taken << "\n";
    std::cout << "takers served: " << tank.served << "\n";
    std::cout << "level never below 0: " << (tank.lowest >= 0 ? "True" : "False") << "\n";
    std::cout << "units left: " << tank.level() << "\n";
}
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: stdlib. std::condition_variable::wait with a predicate tests the guard after each wakeup.
JavaGitHub
import java.util.ArrayList;
import java.util.List;

public class Main {
    static class Tank {
        private int level = 0;
        int lowest = 0; // the lowest level seen after a take
        int filled = 0;
        int taken = 0;
        int served = 0;

        synchronized void take(int amount) throws InterruptedException {
            // Guarded suspension: wait in a loop until the guard is true.
            while (level < amount) {
                wait();
            }
            level -= amount;
            lowest = Math.min(lowest, level);
            taken += amount;
            served++;
        }

        synchronized void fill(int amount) {
            level += amount;
            filled += amount;
            notifyAll(); // each waiting taker checks its guard again
        }

        synchronized int level() {
            return level;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Tank tank = new Tank();
        int[] amounts = {5, 3, 8};
        List<Thread> takers = new ArrayList<>();
        for (int a : amounts) {
            Thread t = new Thread(() -> {
                try {
                    tank.take(a);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
            takers.add(t);
            t.start();
        }
        for (int i = 0; i < 10; i++) tank.fill(2);
        for (Thread t : takers) t.join();

        synchronized (tank) {
            System.out.println("units filled: " + tank.filled);
            System.out.println("units taken: " + tank.taken);
            System.out.println("takers served: " + tank.served);
            System.out.println("level never below 0: " + (tank.lowest >= 0 ? "True" : "False"));
        }
        System.out.println("units left: " + tank.level());
    }
}
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: native. synchronized methods with wait() in a while loop and notifyAll().
using System;
using System.Collections.Generic;
using System.Threading;

class Tank
{
    private readonly object gate = new object();
    private int level = 0;
    public int Lowest, Filled, Taken, Served; // read after the threads end

    public void Take(int amount)
    {
        lock (gate)
        {
            // Guarded suspension: wait in a loop until the guard is true.
            while (level < amount) Monitor.Wait(gate);
            level -= amount;
            Lowest = Math.Min(Lowest, level);
            Taken += amount;
            Served++;
        }
    }

    public void Fill(int amount)
    {
        lock (gate)
        {
            level += amount;
            Filled += amount;
            Monitor.PulseAll(gate); // each waiting taker checks its guard again
        }
    }

    public int Level()
    {
        lock (gate) return level;
    }
}

class Program
{
    static void Main()
    {
        var tank = new Tank();
        int[] amounts = { 5, 3, 8 };
        var takers = new List<Thread>();
        foreach (int a in amounts)
        {
            var t = new Thread(() => tank.Take(a));
            takers.Add(t);
            t.Start();
        }
        for (int i = 0; i < 10; i++) tank.Fill(2);
        foreach (var t in takers) t.Join();

        Console.WriteLine("units filled: " + tank.Filled);
        Console.WriteLine("units taken: " + tank.Taken);
        Console.WriteLine("takers served: " + tank.Served);
        Console.WriteLine("level never below 0: " + (tank.Lowest >= 0 ? "True" : "False"));
        Console.WriteLine("units left: " + tank.Level());
    }
}
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: stdlib. lock with Monitor.Wait in a while loop and Monitor.PulseAll.
JavaScriptGitHub
// The tasks share one thread. A waiting task keeps a promise in a list.
class Tank {
  constructor() {
    this.level = 0;
    this.lowest = 0; // the lowest level seen after a take
    this.filled = 0;
    this.taken = 0;
    this.served = 0;
    this.waiters = [];
  }

  async take(amount) {
    // Guarded suspension: wait in a loop until the guard is true.
    while (this.level < amount) {
      await new Promise((resolve) => this.waiters.push(resolve));
    }
    this.level -= amount;
    this.lowest = Math.min(this.lowest, this.level);
    this.taken += amount;
    this.served++;
  }

  fill(amount) {
    this.level += amount;
    this.filled += amount;
    const waiters = this.waiters; // each waiting taker checks its guard again
    this.waiters = [];
    for (const resolve of waiters) resolve();
  }
}

const tick = () => new Promise((resolve) => setImmediate(resolve));

async function main() {
  const tank = new Tank();
  const takers = [5, 3, 8].map((a) => tank.take(a));
  for (let i = 0; i < 10; i++) {
    tank.fill(2);
    await tick();
  }
  await Promise.all(takers);

  console.log("units filled:", tank.filled);
  console.log("units taken:", tank.taken);
  console.log("takers served:", tank.served);
  console.log("level never below 0:", tank.lowest >= 0 ? "True" : "False");
  console.log("units left:", tank.level);
}

main();
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: idiom. The tasks share one thread, and a waiting task keeps a promise in a list that fill resolves; the task then tests its guard again.
TypeScriptGitHub
// The tasks share one thread. A waiting task keeps a promise in a list.
class Tank {
  level: number;
  lowest: number;
  filled: number;
  taken: number;
  served: number;
  waiters: Array<() => void>;

  constructor() {
    this.level = 0;
    this.lowest = 0; // the lowest level seen after a take
    this.filled = 0;
    this.taken = 0;
    this.served = 0;
    this.waiters = [];
  }

  async take(amount: number): Promise<void> {
    // Guarded suspension: wait in a loop until the guard is true.
    while (this.level < amount) {
      await new Promise<void>((resolve) => this.waiters.push(resolve));
    }
    this.level -= amount;
    this.lowest = Math.min(this.lowest, this.level);
    this.taken += amount;
    this.served++;
  }

  fill(amount: number): void {
    this.level += amount;
    this.filled += amount;
    const waiters = this.waiters; // each waiting taker checks its guard again
    this.waiters = [];
    for (const resolve of waiters) resolve();
  }
}

const tick = (): Promise<void> => new Promise<void>((resolve) => setImmediate(resolve));

async function main(): Promise<void> {
  const tank = new Tank();
  const takers = [5, 3, 8].map((a) => tank.take(a));
  for (let i = 0; i < 10; i++) {
    tank.fill(2);
    await tick();
  }
  await Promise.all(takers);

  console.log("units filled:", tank.filled);
  console.log("units taken:", tank.taken);
  console.log("takers served:", tank.served);
  console.log("level never below 0:", tank.lowest >= 0 ? "True" : "False");
  console.log("units left:", tank.level);
}

main();
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: idiom. The tasks share one thread, and a waiting task keeps a promise in a list that fill resolves; the task then tests its guard again.
package main

import (
	"fmt"
	"sync"
)

type Tank struct {
	mu                            sync.Mutex
	cond                          *sync.Cond
	level                         int
	lowest, filled, taken, served int
}

func NewTank() *Tank {
	t := &Tank{}
	t.cond = sync.NewCond(&t.mu)
	return t
}

func (t *Tank) Take(amount int) {
	t.mu.Lock()
	defer t.mu.Unlock()
	// Guarded suspension: wait in a loop until the guard is true.
	for t.level < amount {
		t.cond.Wait()
	}
	t.level -= amount
	t.lowest = min(t.lowest, t.level)
	t.taken += amount
	t.served++
}

func (t *Tank) Fill(amount int) {
	t.mu.Lock()
	defer t.mu.Unlock()
	t.level += amount
	t.filled += amount
	t.cond.Broadcast() // each waiting taker checks its guard again
}

func main() {
	tank := NewTank()
	amounts := []int{5, 3, 8}
	var wg sync.WaitGroup
	for _, a := range amounts {
		wg.Add(1)
		go func() {
			defer wg.Done()
			tank.Take(a)
		}()
	}
	for i := 0; i < 10; i++ {
		tank.Fill(2)
	}
	wg.Wait()

	tank.mu.Lock()
	defer tank.mu.Unlock()
	fmt.Println("units filled:", tank.filled)
	fmt.Println("units taken:", tank.taken)
	fmt.Println("takers served:", tank.served)
	fmt.Println("level never below 0:", map[bool]string{true: "True", false: "False"}[tank.lowest >= 0])
	fmt.Println("units left:", tank.level)
}
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: stdlib. sync.Cond with Wait in a for loop and Broadcast.
RustGitHub
use std::sync::{Arc, Condvar, Mutex};
use std::thread;

#[derive(Default)]
struct State {
    level: i32,
    lowest: i32, // the lowest level seen after a take
    filled: i32,
    taken: i32,
    served: i32,
}

struct Tank {
    state: Mutex<State>,
    cond: Condvar,
}

impl Tank {
    fn take(&self, amount: i32) {
        let guard = self.state.lock().unwrap();
        // Guarded suspension: wait while the guard is false.
        let mut s = self.cond.wait_while(guard, |s| s.level < amount).unwrap();
        s.level -= amount;
        s.lowest = s.lowest.min(s.level);
        s.taken += amount;
        s.served += 1;
    }

    fn fill(&self, amount: i32) {
        let mut s = self.state.lock().unwrap();
        s.level += amount;
        s.filled += amount;
        self.cond.notify_all(); // each waiting taker checks its guard again
    }
}

fn main() {
    let tank = Arc::new(Tank { state: Mutex::new(State::default()), cond: Condvar::new() });
    let takers: Vec<_> = [5, 3, 8]
        .into_iter()
        .map(|a| {
            let tank = Arc::clone(&tank);
            thread::spawn(move || tank.take(a))
        })
        .collect();
    for _ in 0..10 {
        tank.fill(2);
    }
    for t in takers {
        t.join().unwrap();
    }

    let s = tank.state.lock().unwrap();
    println!("units filled: {}", s.filled);
    println!("units taken: {}", s.taken);
    println!("takers served: {}", s.served);
    println!("level never below 0: {}", if s.lowest >= 0 { "True" } else { "False" });
    println!("units left: {}", s.level);
}
Output
units filled: 20
units taken: 16
takers served: 3
level never below 0: True
units left: 4
  • Verdict: stdlib. Condvar::wait_while waits while the guard is false and returns the MutexGuard.

Consequences

Benefits:

  • A waiting thread does not use the processor, because it blocks on the condition variable until a notification.2
  • The guard and the operation run under the same lock, so no other thread can change the state between the test and the operation.
  • The caller does not need to know when the state changes. In Java, the wait() and notify() methods of the Object class assist with guarded suspension.1

Liabilities:

  • The pattern blocks. If a method call is suspended for too long, the overall program slows down or stops while it waits for the precondition.1
  • Every guard must be checked again each time the wait returns, to protect against spurious wakeups.2 An if in place of the loop is a bug that tests may not show.
  • A thread that changes the state must notify the waiting threads, or they wait forever. Each Cond in Go has an associated Locker, which must be held when the condition changes and when Wait is called.5

This program tests the guard with if. Two takers wait for 5 units, the main thread adds 5 units and notifies both, and both take 5:

This code runs but gives a wrong answer on purpose.

import threading

cond = threading.Condition()
level = 0
waiting = 0


def take(amount):
    global level, waiting
    with cond:
        # Wrong: "if" checks the guard only once, before the wait.
        if level < amount:
            waiting += 1
            cond.wait()
        level -= amount


takers = [threading.Thread(target=take, args=(5,)) for _ in range(2)]
for t in takers:
    t.start()
while True:  # wait until both takers wait
    with cond:
        if waiting == 2:
            level += 5  # enough for one taker only
            cond.notify_all()
            break
for t in takers:
    t.join()
print("level after both takers:", level)
Output
level after both takers: -5

With while level < amount, the second taker tests the guard again, finds a level of 0, and waits again.

When not to use it

Use guarded suspension only when the call will be suspended for a finite and reasonable period of time.1 If the suspension can be indefinite or unacceptably long, the balking pattern may be preferred.1 In Go, many simple uses are better served by channels than a Cond.5

  • Wait with a timeout. The guarded method gives up after a time limit and reports that it was not served. Python's wait_for() automates the condition check and eases the computation of timeouts.3
import threading

cond = threading.Condition()
level = 2


def take(amount, timeout):
    """Wait at most timeout seconds for the guard. Return True if served."""
    global level
    with cond:
        if not cond.wait_for(lambda: level >= amount, timeout):
            return False
        level -= amount
        return True


print("take 5 with a level of 2, served:", take(5, timeout=0.2))
print("level:", level)
print("take 2 with a level of 2, served:", take(2, timeout=0.2))
print("level:", level)
Output
take 5 with a level of 2, served: False
level: 2
take 2 with a level of 2, served: True
level: 0
  • Predicate wait. Some libraries put the loop inside one call. Rust's wait_while blocks the thread until the condition becomes false: it checks the condition at once, and if it is not met, it waits for the next notification and checks again.2
  • Notify one or notify all. Notify one waiting thread when one state change can be interesting for only one waiting thread, as when a producer adds one item to a buffer for one consumer.3 Notify all when the waiting threads have different guards, as the takers in the example do.

A queue whose get waits while the queue is empty is guarded suspension, and it is the consumer side of producer-consumer.1 A monitor object puts guarded methods behind one lock for the whole object.

Known uses

  • Java Object.wait() and notify() inside synchronized methods.1
  • Python threading.Condition with wait() and wait_for().3
  • Go sync.Cond with Wait, Signal and Broadcast.5
  • Rust std::sync::Condvar with wait and wait_while.2

References

  1. Guarded suspension, Wikipedia, lead; Usage; Implementation
  2. The Rust Standard Library, std::sync::Condvar, the type description; wait; wait_while
  3. threading, Thread-based parallelism, Python documentation, Condition Objects
  4. Java SE 21 API, java.lang.Object, wait(long, int)
  5. Go standard library, package sync, type Cond; func (*Cond) Wait

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/GA9K7G/text.yaml