Patternadvanced
Half-Sync/Half-Async
Also called half-sync/half-async, half sync half async, hsha.
Half-Sync/Half-Async splits a concurrent system into layers. Short handlers react to events and never block, threads run the long tasks with blocking calls, and a queue joins the two layers.
- Family
- concurrency
- Intent
- Decouple synchronous I/O from asynchronous I/O in a system to simplify concurrent programming effort without degrading execution efficiency.
Intent
The Half-Sync/Half-Async pattern decouples synchronous I/O from asynchronous I/O in a system to simplify concurrent programming effort without degrading execution efficiency.1 Higher-level tasks use a synchronous I/O model, which simplifies concurrent programming. Lower-level tasks use an asynchronous I/O model, which enhances execution efficiency.1
Problem
The paper's example is the BSD UNIX networking subsystem. The kernel performs I/O asynchronously in response to device interrupts, and user-level applications perform I/O synchronously.1 Two forces pull in opposite directions:1
- Programming simplicity. Asynchrony can cause subtle timing problems and race conditions when an interrupt handler preempts the current thread of control. Programs that use synchronous I/O can block awaiting the completion of I/O operations and keep their state in a runtime stack of activation records, rather than in separate data structures.1
- Execution efficiency. The asynchronous I/O model maps efficiently onto hardware devices that are driven by interrupts. A completely synchronous model may be inefficient if each source of events is associated with a separate process or thread, because each one needs a stack and a set of registers to block.1
Solution
Higher-level tasks, such as database queries or file transfers, use a synchronous I/O model. Lower-level tasks, such as servicing interrupts from network controllers, use an asynchronous I/O model. A Queueing layer mediates communication between the two layers.1 There are usually more high-level tasks than low-level tasks in a system, so the pattern localizes the complexity of asynchronous processing within a single layer.1 The participants are:1
- The Synchronous task layer performs high-level I/O operations. Its tasks are active objects that have their own run-time stack and registers, so they can block. In BSD UNIX, this layer is the user processes.1
- The Queueing layer provides a synchronization and buffering point between the two task layers. In BSD UNIX, it is the Socket layer.1
- The Asynchronous task layer handles lower-level events from multiple external event sources. Its tasks are passive objects without their own run-time stack, so they cannot block indefinitely on any single source of events. In BSD UNIX, it is the kernel.1
- The External event sources, such as network interfaces and disk controllers, generate the events.1
sync layer: worker 1 worker 2 worker 3 (threads that block)
\ | /
queueing layer: [ message queue: get blocks ]
|
async layer: event loop: on_event(e) -> put e, return at once
|
event sources: network interfaces, timers, devices
The two layers communicate in a "producer/consumer" manner by passing messages.1
Example
The example files receive 100 events in the asynchronous layer. Each handler only puts a request on the queue and returns. Four worker threads form the synchronous layer: each one blocks on the queue and then runs a blocking call for the request. The demo holds the workers at a gate until the event source ends, so the program can count the requests that wait in the queueing layer. The Python version uses an asyncio event loop for the asynchronous layer and queue.Queue for the queueing layer, a queue that is useful when information must be exchanged safely between multiple threads.2 The program prints:
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
import asyncio
import queue
import threading
import time
requests = queue.Queue() # the queueing layer
gate = threading.Event() # lets the demo hold the sync layer
results = []
results_lock = threading.Lock()
def worker():
"""Sync layer: blocks on the queue, then runs a blocking call."""
gate.wait()
while True:
request = requests.get()
if request is None:
return
time.sleep(0.001) # a blocking call, such as a database query
with results_lock:
results.append(request)
async def event_source(on_event):
"""Async layer: one event loop thread calls a short handler per event."""
for event_id in range(100):
on_event(event_id)
await asyncio.sleep(0)
received = 0
def on_event(event_id):
global received
received += 1
requests.put_nowait(event_id) # never blocks the event loop
workers = [threading.Thread(target=worker) for _ in range(4)]
for w in workers:
w.start()
asyncio.run(event_source(on_event))
print("events received by the async layer:", received)
print("requests in the queueing layer before the sync layer starts:", requests.qsize())
gate.set()
for _ in workers:
requests.put(None)
for w in workers:
w.join()
print("requests done by the sync layer:", len(results))
print("sum of request ids:", sum(results))
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: stdlib.
asynciogives the event loop of the async layer,queue.Queueis the queueing layer, andthreadinggives the sync layer.
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <mutex>
#include <optional>
#include <thread>
#include <vector>
// The queueing layer: put never blocks, get blocks until an item or close.
class RequestQueue {
public:
void put(int request) {
{ std::lock_guard<std::mutex> lock(mutex_); items_.push_back(request); }
ready_.notify_one();
}
std::optional<int> get() {
std::unique_lock<std::mutex> lock(mutex_);
ready_.wait(lock, [this] { return !items_.empty() || closed_; });
if (items_.empty()) return std::nullopt;
int request = items_.front();
items_.pop_front();
return request;
}
void close() {
{ std::lock_guard<std::mutex> lock(mutex_); closed_ = true; }
ready_.notify_all();
}
std::size_t size() {
std::lock_guard<std::mutex> lock(mutex_);
return items_.size();
}
private:
std::mutex mutex_;
std::condition_variable ready_;
std::deque<int> items_;
bool closed_ = false;
};
int main() {
RequestQueue requests;
std::mutex gate_mutex;
std::condition_variable gate_cv;
bool gate_open = false; // lets the demo hold the sync layer
std::atomic<int> done{0};
std::atomic<long> sum{0};
int received = 0;
std::vector<std::thread> workers;
for (int i = 0; i < 4; ++i) {
workers.emplace_back([&] {
{
std::unique_lock<std::mutex> lock(gate_mutex);
gate_cv.wait(lock, [&] { return gate_open; });
}
while (auto request = requests.get()) {
std::this_thread::sleep_for(std::chrono::milliseconds(1)); // a blocking call
++done;
sum += *request;
}
});
}
// Async layer: a short handler that never blocks.
auto on_event = [&](int event_id) { ++received; requests.put(event_id); };
std::thread event_source([&] { for (int id = 0; id < 100; ++id) on_event(id); });
event_source.join();
std::cout << "events received by the async layer: " << received << "\n";
std::cout << "requests in the queueing layer before the sync layer starts: " << requests.size() << "\n";
{ std::lock_guard<std::mutex> lock(gate_mutex); gate_open = true; }
gate_cv.notify_all();
requests.close();
for (auto& w : workers) w.join();
std::cout << "requests done by the sync layer: " << done << "\n";
std::cout << "sum of request ids: " << sum << "\n";
}
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: library. The standard library has no blocking queue, so
RequestQueuebuilds the queueing layer fromstd::mutexandstd::condition_variable.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
public class Main {
static final LinkedBlockingQueue<Integer> requests = new LinkedBlockingQueue<>(); // queueing layer
static final CountDownLatch gate = new CountDownLatch(1); // lets the demo hold the sync layer
static final AtomicInteger done = new AtomicInteger();
static final AtomicLong sum = new AtomicLong();
static int received = 0;
// Async layer: a short handler that never blocks.
static void onEvent(int eventId) {
received++;
requests.offer(eventId);
}
public static void main(String[] args) throws InterruptedException {
List<Thread> workers = new ArrayList<>();
for (int i = 0; i < 4; i++) {
Thread w = new Thread(() -> {
try {
gate.await();
while (true) {
int request = requests.take(); // the sync layer blocks here
if (request < 0) return;
Thread.sleep(1); // a blocking call, such as a database query
done.incrementAndGet();
sum.addAndGet(request);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
w.start();
workers.add(w);
}
Thread eventSource = new Thread(() -> {
for (int id = 0; id < 100; id++) onEvent(id);
});
eventSource.start();
eventSource.join();
System.out.println("events received by the async layer: " + received);
System.out.println("requests in the queueing layer before the sync layer starts: " + requests.size());
gate.countDown();
for (int i = 0; i < 4; i++) requests.put(-1);
for (Thread w : workers) w.join();
System.out.println("requests done by the sync layer: " + done.get());
System.out.println("sum of request ids: " + sum.get());
}
}
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: stdlib.
LinkedBlockingQueueis the queueing layer:offerreturns at once for the event handler, andtakeblocks the worker threads.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
class Program
{
static readonly BlockingCollection<int> requests = new BlockingCollection<int>(); // queueing layer
static readonly ManualResetEventSlim gate = new ManualResetEventSlim(false);
static int received, done;
static long sum;
// Async layer: a short handler that never blocks.
static void OnEvent(int eventId)
{
received++;
requests.Add(eventId);
}
static void Main()
{
var workers = new List<Thread>();
for (int i = 0; i < 4; i++)
{
var w = new Thread(() =>
{
gate.Wait();
foreach (int request in requests.GetConsumingEnumerable()) // blocks for each item
{
Thread.Sleep(1); // a blocking call, such as a database query
Interlocked.Increment(ref done);
Interlocked.Add(ref sum, request);
}
});
w.Start();
workers.Add(w);
}
var eventSource = new Thread(() => { for (int id = 0; id < 100; id++) OnEvent(id); });
eventSource.Start();
eventSource.Join();
Console.WriteLine("events received by the async layer: " + received);
Console.WriteLine("requests in the queueing layer before the sync layer starts: " + requests.Count);
gate.Set();
requests.CompleteAdding();
workers.ForEach(w => w.Join());
Console.WriteLine("requests done by the sync layer: " + done);
Console.WriteLine("sum of request ids: " + sum);
}
}
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: stdlib.
BlockingCollection<T>is the queueing layer, andGetConsumingEnumerableblocks each worker until an item arrives or adding is complete.
const { Worker } = require("node:worker_threads");
// Sync layer: each worker thread runs one request at a time with a blocking call.
const workerCode = `
const { parentPort } = require("node:worker_threads");
const pause = new Int32Array(new SharedArrayBuffer(4));
parentPort.on("message", (request) => {
if (request === null) {
parentPort.close();
return;
}
Atomics.wait(pause, 0, 0, 1); // a blocking call, such as a database query
parentPort.postMessage(request);
});
parentPort.postMessage("ready");
`;
const requests = []; // the queueing layer, kept by the main thread
const idle = [];
let gateOpen = false; // lets the demo hold the sync layer
let received = 0;
let done = 0;
let sum = 0;
function dispatch() {
while (gateOpen && idle.length > 0) {
const worker = idle.shift();
worker.postMessage(requests.length > 0 ? requests.shift() : null);
}
}
const workers = [];
for (let i = 0; i < 4; i++) {
const worker = new Worker(workerCode, { eval: true });
worker.on("message", (message) => {
if (message !== "ready") {
done += 1;
sum += message;
}
idle.push(worker);
dispatch();
});
workers.push(new Promise((resolve) => worker.on("exit", resolve)));
}
// Async layer: the event loop calls a short handler per event.
function onEvent(eventId) {
received += 1;
requests.push(eventId); // never blocks the event loop
}
let next = 0;
function eventSource() {
if (next < 100) {
onEvent(next++);
setImmediate(eventSource);
return;
}
console.log("events received by the async layer:", received);
console.log("requests in the queueing layer before the sync layer starts:", requests.length);
gateOpen = true;
dispatch();
Promise.all(workers).then(() => {
console.log("requests done by the sync layer:", done);
console.log("sum of request ids:", sum);
});
}
eventSource();
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: idiom. The main thread runs the event loop and must not block, so it keeps the queue and hands one request to each idle worker thread. The worker code blocks with
Atomics.wait.
import { Worker } from "node:worker_threads";
// Sync layer: each worker thread runs one request at a time with a blocking call.
const workerCode = `
const { parentPort } = require("node:worker_threads");
const pause = new Int32Array(new SharedArrayBuffer(4));
parentPort.on("message", (request) => {
if (request === null) {
parentPort.close();
return;
}
Atomics.wait(pause, 0, 0, 1); // a blocking call, such as a database query
parentPort.postMessage(request);
});
parentPort.postMessage("ready");
`;
const requests: number[] = []; // the queueing layer, kept by the main thread
const idle: Worker[] = [];
let gateOpen = false; // lets the demo hold the sync layer
let received = 0;
let done = 0;
let sum = 0;
function dispatch(): void {
while (gateOpen && idle.length > 0) {
const worker = idle.shift();
worker.postMessage(requests.length > 0 ? requests.shift() : null);
}
}
const workers: Promise<number>[] = [];
for (let i = 0; i < 4; i++) {
const worker = new Worker(workerCode, { eval: true });
worker.on("message", (message: number | "ready") => {
if (message !== "ready") {
done += 1;
sum += message;
}
idle.push(worker);
dispatch();
});
workers.push(new Promise<number>((resolve) => worker.on("exit", resolve)));
}
// Async layer: the event loop calls a short handler per event.
function onEvent(eventId: number): void {
received += 1;
requests.push(eventId); // never blocks the event loop
}
let next = 0;
function eventSource(): void {
if (next < 100) {
onEvent(next++);
setImmediate(eventSource);
return;
}
console.log("events received by the async layer:", received);
console.log("requests in the queueing layer before the sync layer starts:", requests.length);
gateOpen = true;
dispatch();
Promise.all(workers).then(() => {
console.log("requests done by the sync layer:", done);
console.log("sum of request ids:", sum);
});
}
eventSource();
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: idiom. The main thread runs the event loop and must not block, so it keeps the queue and hands one request to each idle worker thread. The worker code blocks with
Atomics.wait.
package main
import (
"fmt"
"sync"
"sync/atomic"
"time"
)
func main() {
requests := make(chan int, 100) // the queueing layer: a buffered channel
gate := make(chan struct{}) // lets the demo hold the sync layer
var done, sum atomic.Int64
received := 0
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-gate
for request := range requests { // the sync layer blocks here
time.Sleep(time.Millisecond) // a blocking call, such as a database query
done.Add(1)
sum.Add(int64(request))
}
}()
}
// Async layer: a short handler that never blocks while the buffer has room.
onEvent := func(eventID int) {
received++
requests <- eventID
}
sourceDone := make(chan struct{})
go func() {
for id := 0; id < 100; id++ {
onEvent(id)
}
close(sourceDone)
}()
<-sourceDone
fmt.Println("events received by the async layer:", received)
fmt.Println("requests in the queueing layer before the sync layer starts:", len(requests))
close(gate)
close(requests)
wg.Wait()
fmt.Println("requests done by the sync layer:", done.Load())
fmt.Println("sum of request ids:", sum.Load())
}
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: native. A buffered channel is the queueing layer: a send blocks only when the buffer is full, and
rangeover the channel blocks each worker until a value arrives or the channel is closed.
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Barrier, Mutex};
use std::thread;
use std::time::Duration;
fn main() {
let (tx, rx) = mpsc::channel::<u64>(); // the queueing layer
let rx = Arc::new(Mutex::new(rx)); // shared by the sync workers
let gate = Arc::new(Barrier::new(5)); // lets the demo hold the sync layer
let done = Arc::new(AtomicU64::new(0));
let sum = Arc::new(AtomicU64::new(0));
let pending = Arc::new(AtomicU64::new(0)); // requests waiting in the channel
let workers: Vec<_> = (0..4)
.map(|_| {
let (rx, gate, done, sum, pending) =
(rx.clone(), gate.clone(), done.clone(), sum.clone(), pending.clone());
thread::spawn(move || {
gate.wait();
loop {
let next = rx.lock().unwrap().recv(); // the sync layer blocks here
let Ok(request) = next else { return };
pending.fetch_sub(1, Ordering::Relaxed);
thread::sleep(Duration::from_millis(1)); // a blocking call
done.fetch_add(1, Ordering::Relaxed);
sum.fetch_add(request, Ordering::Relaxed);
}
})
})
.collect();
// Async layer: a short handler that never blocks.
let source_pending = pending.clone();
let source = thread::spawn(move || {
let mut received = 0;
let on_event = |id: u64, received: &mut u64| {
*received += 1;
source_pending.fetch_add(1, Ordering::Relaxed);
tx.send(id).unwrap();
};
for id in 0..100 {
on_event(id, &mut received);
}
(received, tx)
});
let (received, tx) = source.join().unwrap();
let queued = pending.load(Ordering::Relaxed);
println!("events received by the async layer: {}", received);
println!("requests in the queueing layer before the sync layer starts: {}", queued);
drop(tx);
gate.wait();
for w in workers {
w.join().unwrap();
}
println!("requests done by the sync layer: {}", done.load(Ordering::Relaxed));
println!("sum of request ids: {}", sum.load(Ordering::Relaxed));
}
events received by the async layer: 100
requests in the queueing layer before the sync layer starts: 100
requests done by the sync layer: 100
sum of request ids: 4950
- Verdict: stdlib.
mpsc::channelis unbounded, sosendnever blocks. It has one receiver, so the workers share it behind aMutex.
Consequences
Benefits:1
- Higher-level tasks are simplified because they are shielded from lower-level asynchronous I/O. Complex concurrency control, interrupt handling, and timing issues are delegated to the Asynchronous task layer.1
- Synchronization policies in each layer are decoupled. In the single-threaded BSD UNIX kernel, the Asynchronous layer controls concurrency by raising and lowering CPU interrupt levels, while user processes use semaphores, message queues, condition variables, and record locks.1
- Inter-layer communication is localized at a single point, because the Queueing layer mediates all interaction.1
- Performance is improved on multi-processors. One processor can be dedicated to a thread that transfers a large stream of data.1
Liabilities:1
- A boundary-crossing penalty may be incurred from synchronization, data copying, and context switching overhead when data moves through the Queueing layer. The socket layer in BSD UNIX accounts for a large percentage of the overall TCP/IP networking overhead.1
- Asynchronous I/O for higher-level tasks is lacking. The system I/O structure may prevent applications from utilizing the hardware efficiently, even if external devices support asynchronous overlap of computation and communication.1
The asynchronous layer must not block. The asyncio documentation warns that file operations can block the event loop, and runs them in a thread pool.3 In the block below, four handlers make a blocking call on the event loop thread, so a timer that is due after 10 ms runs only after all of them:
This code runs but gives a wrong answer on purpose.
import asyncio
import time
async def main():
loop = asyncio.get_running_loop()
order = []
done = loop.create_future()
start = time.monotonic()
def slow_handler():
time.sleep(0.05) # a blocking call in the async layer
order.append("slow")
def timer():
order.append("timer")
done.set_result(time.monotonic() - start)
loop.call_later(0.01, timer)
for _ in range(4):
loop.call_soon(slow_handler)
elapsed = await done
print("order:", order)
print("timer was late by at least 0.15 s:", elapsed - 0.01 >= 0.15)
asyncio.run(main())
order: ['slow', 'slow', 'slow', 'slow', 'timer']
timer was late by at least 0.15 s: True
When not to use it
- Every task is short and never blocks. Then the asynchronous layer can do all the work, and the queue only adds the boundary-crossing penalty.1
- Higher-level tasks must use asynchronous I/O to reach the full speed of the devices. The pattern hides that I/O from them.1
- The queue has no bound and events can arrive faster than workers finish them. Systems cannot devote an unlimited amount of resources to buffer messages in the Queueing layer, so the layer needs flow control.1
Variants and related patterns
- Active Object. The Synchronous task layer uses the Active Object pattern.1
- Reactor. The Asynchronous task layer may use the Reactor pattern to demultiplex events from multiple sources of events.1
- Facade and Mediator. The Queueing layer provides a Facade that simplifies the interface to the Asynchronous task layer, and it is also a Mediator that coordinates the exchange of data between the two task layers.1
- Thread per handle. In the Asynchronous layer of MT-Orbix, a separate thread is associated with each handle that is connected to a client, and each thread blocks synchronously reading CORBA requests.1
- Leader/Followers. POSA2 lists Half-Sync/Half-Async and Leader/Followers among its 17 patterns.4
The data can also go from the asynchronous layer to a synchronous call and back. In asyncio, loop.run_in_executor arranges for a function to be called in an executor, and the default executor is a ThreadPoolExecutor.3 The coroutine waits for the result and the event loop keeps running other callbacks:
import asyncio
import threading
import time
def blocking_lookup(n):
time.sleep(0.1) # a synchronous call in a pool thread
return n * n, threading.current_thread() is threading.main_thread()
async def main():
loop = asyncio.get_running_loop()
ticks = 0
async def ticker():
nonlocal ticks
while True:
ticks += 1
await asyncio.sleep(0.01)
task = asyncio.create_task(ticker())
result, on_main = await loop.run_in_executor(None, blocking_lookup, 12)
task.cancel()
print("result:", result)
print("blocking call ran on the event loop thread:", on_main)
print("event loop ran other work during the call:", ticks > 1)
asyncio.run(main())
result: 144
blocking call ran on the event loop thread: False
event loop ran other work during the call: True
Known uses
- UNIX kernels. The BSD UNIX networking subsystem and the original System V UNIX STREAMS framework use the pattern. The Queueing layer is the Socket layer in BSD and the STREAM heads in System V STREAMS.1
- MT-Orbix. The multi-threaded version of Orbix 1.3 uses several variations of the pattern to dispatch CORBA remote operations in a concurrent server.1
- Motorola Iridium. An application-level Gateway that routes messages between satellites and ground control stations uses the pattern. The ASX Reactor handles events asynchronously, the ASX Message Queue is the Queueing layer, and the ASX Task class implements the synchronous active objects.1
- Operating systems. The pattern is widely used in operating systems such as UNIX, Mach, Windows NT, and VMS.1
References
- Douglas C. Schmidt and Charles D. Cranor, Half-Sync/Half-Async: An Architectural Pattern for Efficient and Well-structured Concurrent I/O, Abstract; 1 Intent; 2 Motivation; 3 Solution; 5 Structure and Participants; 7 Consequences; 8 Implementation; 10 Related Patterns; 11 Known Uses
- queue, A synchronized queue class, Python documentation, introduction
- Event Loop, asyncio, Python documentation, Scheduling callbacks; Executing code in thread or process pools
- Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Overview, the 17 patterns
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 | W4 complete |
|
Tag QGA6WS Edit this page History Report an error Markdown