Programming Search⌘K

Patterncore

Scoped Locking

Also called scoped lock, lock guard, guard, synchronized block.

Scoped Locking takes a lock when control enters a scope and releases it when control leaves the scope by any path, so no return or exception can leave the lock held.

Family
concurrency
Intent
Tie a lock to a scope, so that the lock is acquired at the start of a critical section and always released at its end.
Also called
Synchronized Block, Object-Construction-is-Resource-Acquisition, Guard

Intent

The Scoped Locking C++ idiom ensures that a lock is acquired when control enters a scope and the lock is released automatically when control leaves the scope.1 It is also known as Synchronized Block, Object-Construction-is-Resource-Acquisition and Guard.1

Problem

The paper's example is the hit counter of a Web server. Its public methods must be serialized to prevent threads from corrupting the state of its internal table as hit counts are updated concurrently.1 When each method calls acquire and release itself, maintenance programmers may forget to release the lock on all return paths out of the method.1 If a later version throws an exception, the lock is not released either.1 If the lock is not released, the Web server process will hang when other threads block indefinitely trying to acquire the lock.1

Solution

Define a guard class whose constructor automatically acquires a lock when control enters a scope and whose destructor automatically releases the lock when control leaves the scope.1 Instantiate instances of the guard class to acquire and release locks in method or block scopes that define critical sections.1

increment(path):
  guard = Guard(lock)        # constructor: lock.acquire()
  if path is bad: return -1  # leaves the scope: lock.release()
  table[path] += 1
  return 0                   # leaves the scope: lock.release()

Languages without destructors get the same effect from a statement. Java defines a programming feature called a synchronized block that implements the Scoped Locking idiom in the language.1 The C# lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock.2 Python locks also support the context management protocol, so a with statement holds the lock for its block.3

Example

The example files show one program in each language. Four workers each add 1,000 hits to one table entry under a scoped lock. Then a call with an empty path takes the early return. The program checks that the lock is free after that return, and that the counter still works. The program prints:

hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
PythonGitHub
import threading

lock = threading.Lock()
table = {}


def increment(path):
    with lock:  # acquired here, released on every way out
        if not path:
            return -1
        table[path] = table.get(path, 0) + 1
        return 0


def worker():
    for _ in range(1000):
        increment("/index")


threads = [threading.Thread(target=worker) for _ in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("hits /index:", table["/index"])
print("bad path returns", increment(""))
print("lock free after the early return:", not lock.locked())
increment("/index")
print("hits /index:", table["/index"])
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: native. A lock is a context manager, so the with statement is the guard.
#include <iostream>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <vector>

std::mutex lock;
std::map<std::string, int> table;

int increment(const std::string& path) {
    std::lock_guard<std::mutex> guard(lock);  // the destructor releases the lock
    if (path.empty()) return -1;
    ++table[path];
    return 0;
}

int main() {
    std::vector<std::thread> threads;
    for (int i = 0; i < 4; ++i) {
        threads.emplace_back([] { for (int j = 0; j < 1000; ++j) increment("/index"); });
    }
    for (auto& t : threads) t.join();
    std::cout << "hits /index: " << table["/index"] << "\n";
    std::cout << "bad path returns " << increment("") << "\n";
    bool free = lock.try_lock();
    if (free) lock.unlock();
    std::cout << "lock free after the early return: " << (free ? "True" : "False") << "\n";
    increment("/index");
    std::cout << "hits /index: " << table["/index"] << "\n";
}
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: native. std::lock_guard is the guard class of the idiom, and its destructor runs on each return path.
JavaGitHub
import java.util.HashMap;
import java.util.Map;

public class Main {
    static final Object lock = new Object();
    static final Map<String, Integer> table = new HashMap<>();

    static int increment(String path) {
        synchronized (lock) {  // released on every way out
            if (path.isEmpty()) return -1;
            table.merge(path, 1, Integer::sum);
            return 0;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[4];
        for (int i = 0; i < 4; i++) {
            threads[i] = new Thread(() -> { for (int j = 0; j < 1000; j++) increment("/index"); });
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        System.out.println("hits /index: " + table.get("/index"));
        System.out.println("bad path returns " + increment(""));
        System.out.println("lock free after the early return: " + (Thread.holdsLock(lock) ? "False" : "True"));
        increment("/index");
        System.out.println("hits /index: " + table.get("/index"));
    }
}
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: native. The synchronized block is the idiom in the language. Thread.holdsLock checks that the current thread no longer holds the monitor.
using System;
using System.Collections.Generic;
using System.Threading;

static class Program
{
    static readonly object Gate = new();
    static readonly Dictionary<string, int> Table = new();

    static int Increment(string path)
    {
        lock (Gate) // released on every way out
        {
            if (path.Length == 0) return -1;
            Table[path] = Table.GetValueOrDefault(path) + 1;
            return 0;
        }
    }

    static void Main()
    {
        var threads = new Thread[4];
        for (int i = 0; i < 4; i++)
        {
            threads[i] = new Thread(() => { for (int j = 0; j < 1000; j++) Increment("/index"); });
            threads[i].Start();
        }
        foreach (var t in threads) t.Join();
        Console.WriteLine($"hits /index: {Table["/index"]}");
        Console.WriteLine($"bad path returns {Increment("")}");
        Console.WriteLine($"lock free after the early return: {!Monitor.IsEntered(Gate)}");
        Increment("/index");
        Console.WriteLine($"hits /index: {Table["/index"]}");
    }
}
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: native. The lock statement is the idiom in the language. Monitor.IsEntered checks that the current thread no longer holds the lock.
JavaScriptGitHub
// One thread, but awaits interleave the workers, so a lock still matters.
class Lock {
  constructor() {
    this.tail = Promise.resolve();
    this.held = false;
  }
  async withLock(body) {
    const previous = this.tail;
    let release;
    this.tail = new Promise((resolve) => (release = resolve));
    await previous;
    this.held = true;
    try {
      return await body();
    } finally {
      this.held = false; // released on every way out
      release();
    }
  }
}

const lock = new Lock();
const table = new Map();

function increment(path) {
  return lock.withLock(async () => {
    if (!path) return -1;
    const count = table.get(path) ?? 0;
    await null; // a pause inside the critical section
    table.set(path, count + 1);
    return 0;
  });
}

async function worker() {
  for (let i = 0; i < 1000; i++) await increment("/index");
}

async function main() {
  await Promise.all([worker(), worker(), worker(), worker()]);
  console.log("hits /index:", table.get("/index"));
  console.log("bad path returns", await increment(""));
  console.log("lock free after the early return:", lock.held ? "False" : "True");
  await increment("/index");
  console.log("hits /index:", table.get("/index"));
}

main();
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: idiom. There is no lock in the language, so the example builds one from promises. withLock releases the lock in finally, which is the scoped form.
TypeScriptGitHub
class Lock {
  private tail: Promise<void> = Promise.resolve();
  held = false;
  async withLock<T>(body: () => Promise<T>): Promise<T> {
    const previous = this.tail;
    let release!: () => void;
    this.tail = new Promise<void>((resolve) => (release = resolve));
    await previous;
    this.held = true;
    try {
      return await body();
    } finally {
      this.held = false; // released on every way out
      release();
    }
  }
}

const lock = new Lock();
const table = new Map<string, number>();

function increment(path: string): Promise<number> {
  return lock.withLock(async () => {
    if (!path) return -1;
    const count = table.get(path) ?? 0;
    await null;
    table.set(path, count + 1);
    return 0;
  });
}

async function worker(): Promise<void> {
  for (let i = 0; i < 1000; i++) await increment("/index");
}

async function main(): Promise<void> {
  await Promise.all([worker(), worker(), worker(), worker()]);
  console.log("hits /index:", table.get("/index"));
  console.log("bad path returns", await increment(""));
  console.log("lock free after the early return:", lock.held ? "False" : "True");
  await increment("/index");
  console.log("hits /index:", table.get("/index"));
}

main();
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: idiom. The generic withLock<T> keeps the type of the value that the critical section returns.
package main

import (
	"fmt"
	"sync"
)

var (
	mu    sync.Mutex
	table = map[string]int{}
)

func increment(path string) int {
	mu.Lock()
	defer mu.Unlock() // runs on every return
	if path == "" {
		return -1
	}
	table[path]++
	return 0
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 1000; j++ {
				increment("/index")
			}
		}()
	}
	wg.Wait()
	fmt.Println("hits /index:", table["/index"])
	fmt.Println("bad path returns", increment(""))
	free := mu.TryLock()
	if free {
		mu.Unlock()
	}
	fmt.Println("lock free after the early return: " + map[bool]string{true: "True", false: "False"}[free])
	increment("/index")
	fmt.Println("hits /index:", table["/index"])
}
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: idiom. Go has no destructors. defer mu.Unlock() right after mu.Lock() gives the same guarantee for the function scope.
RustGitHub
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;

fn increment(table: &Mutex<HashMap<String, i32>>, path: &str) -> i32 {
    let mut guard = table.lock().unwrap(); // the guard unlocks when it is dropped
    if path.is_empty() {
        return -1;
    }
    *guard.entry(path.to_string()).or_insert(0) += 1;
    0
}

fn main() {
    let table = Arc::new(Mutex::new(HashMap::new()));
    let handles: Vec<_> = (0..4)
        .map(|_| {
            let table = Arc::clone(&table);
            thread::spawn(move || {
                for _ in 0..1000 {
                    increment(&table, "/index");
                }
            })
        })
        .collect();
    for h in handles {
        h.join().unwrap();
    }
    println!("hits /index: {}", table.lock().unwrap()["/index"]);
    println!("bad path returns {}", increment(&table, ""));
    let free = table.try_lock().is_ok();
    println!("lock free after the early return: {}", if free { "True" } else { "False" });
    increment(&table, "/index");
    println!("hits /index: {}", table.lock().unwrap()["/index"]);
}
Output
hits /index: 4000
bad path returns -1
lock free after the early return: True
hits /index: 4001
  • Verdict: native. The data is inside the Mutex, so code can reach it only through the guard, and the guard unlocks when it goes out of scope.

Consequences

Benefits:1

  • Increased robustness. Locks will be acquired and released automatically when control enters and leaves critical sections defined by method and block scopes.1
  • Decreased maintenance effort. A change to the method, such as a new return path, cannot forget the release.1

Liabilities:1

  • Potential for deadlock when used recursively. If a method that uses the Scoped Locking idiom calls itself recursively, self-deadlock will occur if the lock is not a recursive mutex.1
  • Limitations with language-specific semantics. Locks may not be released automatically when threads or processes abort or exit inside of a guarded critical section.1

Here is the mistake that the idiom prevents. The early return skips the explicit release:

This code runs but gives a wrong answer on purpose.

import threading

lock = threading.Lock()
table = {}


def increment(path):
    lock.acquire()
    if not path:
        return -1  # returns with the lock held
    table[path] = table.get(path, 0) + 1
    lock.release()
    return 0


increment("")
print("lock still held:", lock.locked())
print("next caller gets the lock:", lock.acquire(timeout=0.1))
Output
lock still held: True
next caller gets the lock: False

When not to use it

  • The lock must be held across scopes, for example taken in one callback and released in another. A guard cannot express that; the Variants section shows explicit accessors.1
  • The data is confined to one thread, or it is immutable. No lock is needed then.
  • A recursive call path takes the same lock, and the lock is not reentrant.1
  • Explicit accessors. A variant of the idiom can be defined to provide explicit accessors to the underlying lock, for code that must release the lock before the scope ends.1
  • Strategized Scoped Locking. A common variant is to apply the parameterized type or polymorphic version of the Strategized Locking pattern, so one guard works for each kind of lock.1
  • Thread-Safe Interface. It ensures that only interface methods apply the Scoped Locking idiom, whereas implementation methods do not, which avoids self-deadlock.1
  • Synchronization patterns. POSA2 puts Scoped Locking with Strategized Locking, Thread-Safe Interface and Double-Checked Locking Optimization.4
  • RAII. The idiom is a special case of a more general C++ idiom where a constructor acquires a resource and a destructor releases the resource.1

A reentrant lock is a synchronization primitive that may be acquired multiple times by the same thread.3 This shows the recursive case with both kinds of lock:

import threading


def nested(lock):
    with lock:  # the outer scope holds the lock
        got = lock.acquire(timeout=0.1)  # a recursive call tries again
        if got:
            lock.release()
        return got


print("Lock, recursive call gets the lock:", nested(threading.Lock()))
print("RLock, recursive call gets the lock:", nested(threading.RLock()))
Output
Lock, recursive call gets the lock: False
RLock, recursive call gets the lock: True

Known uses

  • Booch Components. They were one of the first C++ class libraries to use the Scoped Locking idiom for multithreaded C++ programs.1
  • ACE. The idiom is used extensively throughout the Adaptive Communication Environment.1
  • C++. std::lock_guard is a mutex wrapper that provides a convenient RAII-style mechanism for owning a mutex for the duration of a scoped block.5
  • Rust. The data of a Mutex can only be accessed through the RAII guards returned from lock and try_lock.6
  • Go. The canonical examples of defer are unlocking a mutex or closing a file.7
  • Java and C#. The synchronized block and the lock statement are the idiom in the language.12

References

  1. Douglas C. Schmidt, Scoped Locking (POSA2 chapter draft), Intent; Also Known As; Example; Solution; Variants; Known Uses; Consequences; See Also
  2. The lock statement, C# language reference, Microsoft Learn, introduction
  3. threading, Thread-based parallelism, Python documentation, Lock objects; RLock objects
  4. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Table of Contents, 4 Synchronization Patterns
  5. std::lock_guard, cppreference.com, description
  6. Mutex in std::sync, The Rust Standard Library, description
  7. Effective Go, Defer

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/78MAN6/text.yaml