Patternadvanced
Proactor
Also called proactor pattern.
A proactor starts asynchronous operations and, when each one completes, calls its completion handler, so the program reacts to finished work and not to readiness.
- Family
- concurrency
- Intent
- Let an application start many asynchronous operations at once and dispatch a completion handler for each operation when the operation finishes.
Intent
The Proactor pattern supports the demultiplexing and dispatching of multiple event handlers, which are triggered by the completion of asynchronous events.1 It can be considered to be an asynchronous variant of the synchronous reactor pattern.2
Problem
A server must start many reads and writes, and it must not block a thread for each one. A Reactor tells the program that a handle is ready, and the program then does the operation itself. Some operating systems can do the whole operation: they provide asynchronous I/O subsystems within the kernel.1 The program then needs a way to learn which operation finished and which code must handle the result.
Solution
The paper names these participants.1
- Proactive Initiator. It is any entity in the application that initiates an Asynchronous Operation.1
- Asynchronous Operation Processor. It runs the operations to completion. This component is typically implemented by the OS.1
- Completion Dispatcher. It is responsible for calling back to the application's Completion Handlers when Asynchronous Operations complete.1
- Completion Handler. It holds the application code that uses the result.
initiator --start(op, handler)--> Asynchronous Operation Processor
| runs op (OS, kernel, thread)
v
completion queue
|
Completion Dispatcher: take (handler, result)
|
v
handler(result)
The initiator gives the handler at the start of the operation. The dispatcher calls the handler later, with the result, in a thread that it controls.
Example
The example files show one program in each language. A worker thread is the Asynchronous Operation Processor: it reads two files from a table and puts each completion on a queue. The main thread is the Completion Dispatcher: it takes each completion from the queue and calls its handler. The worker does the operations in order, so the output is the same on each run:
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
import queue
import threading
files = {"a.txt": "hello", "b.txt": "abc"}
operations = queue.Queue() # requests to the processor
completions = queue.Queue() # the completion queue
def processor():
# the Asynchronous Operation Processor: one worker thread
while (op := operations.get()) is not None:
name, handler = op
completions.put((handler, name, len(files[name])))
def start_read(name, handler): # the Proactive Initiator
print("start read", name)
operations.put((name, handler))
def on_read(name, size): # the Completion Handler
print(f"{name} done: {size} bytes")
worker = threading.Thread(target=processor)
worker.start()
start_read("a.txt", on_read)
start_read("b.txt", on_read)
for _ in range(2): # the Completion Dispatcher in the main thread
handler, name, size = completions.get()
handler(name, size)
operations.put(None)
worker.join()
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: stdlib.
queue.Queueis a thread-safe queue, so it can join the worker thread and the dispatcher.asynciogives the same shape with an event loop.
#include <condition_variable>
#include <functional>
#include <iostream>
#include <map>
#include <mutex>
#include <queue>
#include <string>
#include <thread>
using Handler = std::function<void(const std::string&, std::size_t)>;
template <typename T>
class Queue {
public:
void put(T value) {
{ std::lock_guard<std::mutex> lock(m_); q_.push(std::move(value)); }
cv_.notify_one();
}
T take() {
std::unique_lock<std::mutex> lock(m_);
cv_.wait(lock, [this] { return !q_.empty(); });
T value = std::move(q_.front());
q_.pop();
return value;
}
private:
std::mutex m_;
std::condition_variable cv_;
std::queue<T> q_;
};
struct Completion { Handler handler; std::string name; std::size_t size; };
int main() {
const std::map<std::string, std::string> files{{"a.txt", "hello"}, {"b.txt", "abc"}};
Queue<std::pair<std::string, Handler>> operations;
Queue<Completion> completions;
std::thread processor([&] {
for (int i = 0; i < 2; ++i) {
auto [name, handler] = operations.take();
completions.put({handler, name, files.at(name).size()});
}
});
Handler onRead = [](const std::string& name, std::size_t size) {
std::cout << name << " done: " << size << " bytes\n";
};
for (const std::string name : {"a.txt", "b.txt"}) {
std::cout << "start read " << name << "\n";
operations.put({name, onRead});
}
for (int i = 0; i < 2; ++i) {
Completion c = completions.take(); // the Completion Dispatcher
c.handler(c.name, c.size);
}
processor.join();
}
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: idiom. The standard library has threads, a mutex and condition variables but no blocking queue, so the example writes a small one.
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.BiConsumer;
public class Main {
record Completion(BiConsumer<String, Integer> handler, String name, int size) {}
static final Map<String, String> files = Map.of("a.txt", "hello", "b.txt", "abc");
static final BlockingQueue<Completion> completions = new LinkedBlockingQueue<>();
static final BlockingQueue<Object[]> operations = new LinkedBlockingQueue<>();
@SuppressWarnings("unchecked")
public static void main(String[] args) throws InterruptedException {
Thread processor = new Thread(() -> {
try {
for (int i = 0; i < 2; i++) {
Object[] op = operations.take();
String name = (String) op[0];
completions.put(new Completion(
(BiConsumer<String, Integer>) op[1], name, files.get(name).length()));
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
});
processor.start();
BiConsumer<String, Integer> onRead =
(name, size) -> System.out.println(name + " done: " + size + " bytes");
for (String name : new String[] {"a.txt", "b.txt"}) {
System.out.println("start read " + name);
operations.put(new Object[] {name, onRead});
}
for (int i = 0; i < 2; i++) {
Completion c = completions.take(); // the Completion Dispatcher
c.handler().accept(c.name(), c.size());
}
processor.join();
}
}
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: stdlib.
LinkedBlockingQueuejoins the processor thread and the dispatcher. The completion is a record with its handler.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
static class Program
{
static void Main()
{
var files = new Dictionary<string, string> { ["a.txt"] = "hello", ["b.txt"] = "abc" };
var operations = new BlockingCollection<(string Name, Action<string, int> Handler)>();
var completions = new BlockingCollection<(Action<string, int> Handler, string Name, int Size)>();
var processor = new Thread(() =>
{
foreach (var (name, handler) in operations.GetConsumingEnumerable())
{
completions.Add((handler, name, files[name].Length));
}
});
processor.Start();
Action<string, int> onRead = (name, size) => Console.WriteLine($"{name} done: {size} bytes");
foreach (var name in new[] { "a.txt", "b.txt" })
{
Console.WriteLine($"start read {name}");
operations.Add((name, onRead));
}
operations.CompleteAdding();
for (int i = 0; i < 2; i++)
{
var (handler, name, size) = completions.Take(); // the Completion Dispatcher
handler(name, size);
}
processor.Join();
}
}
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: stdlib.
BlockingCollectiongives the two queues, and the handler is anAction<string, int>delegate.
const { readFile, writeFile, mkdtemp } = require("node:fs/promises");
const { tmpdir } = require("node:os");
const path = require("node:path");
function onRead(name, size) {
console.log(`${name} done: ${size} bytes`);
}
async function main() {
const dir = await mkdtemp(path.join(tmpdir(), "proactor-"));
await writeFile(path.join(dir, "a.txt"), "hello");
await writeFile(path.join(dir, "b.txt"), "abc");
const reads = ["a.txt", "b.txt"].map((name) => {
console.log("start read", name);
// the runtime does the read; the promise is the completion
return readFile(path.join(dir, name)).then((data) => [name, data.length]);
});
for (const done of reads) {
const [name, size] = await done; // the event loop dispatches completions
onRead(name, size);
}
}
main();
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: native. A call to
fs.promises.readFilestarts the operation and returns at once. The event loop of the runtime is the completion dispatcher, and the code afterawaitis the completion handler.
type Handler = (name: string, size: number) => void;
const files: Record<string, string> = { "a.txt": "hello", "b.txt": "abc" };
// the Asynchronous Operation Processor: completes each read later
function startRead(name: string, handler: Handler): Promise<void> {
console.log("start read", name);
return new Promise<number>((resolve) => {
setTimeout(() => resolve(files[name].length), 0);
}).then((size) => handler(name, size));
}
const onRead: Handler = (name, size) => {
console.log(`${name} done: ${size} bytes`);
};
async function main(): Promise<void> {
const a = startRead("a.txt", onRead);
const b = startRead("b.txt", onRead);
await Promise.all([a, b]);
}
main();
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: native.
setTimeoutstands in for the operation, and the event loop calls the handler with the result. The typeHandlerfixes the shape of each completion handler.
package main
import "fmt"
type Handler func(name string, size int)
type operation struct {
name string
handler Handler
}
type completion struct {
handler Handler
name string
size int
}
func main() {
files := map[string]string{"a.txt": "hello", "b.txt": "abc"}
operations := make(chan operation)
completions := make(chan completion, 2)
go func() { // the Asynchronous Operation Processor
for op := range operations {
completions <- completion{op.handler, op.name, len(files[op.name])}
}
}()
onRead := func(name string, size int) { fmt.Printf("%s done: %d bytes\n", name, size) }
for _, name := range []string{"a.txt", "b.txt"} {
fmt.Println("start read", name)
operations <- operation{name, onRead}
}
close(operations)
for i := 0; i < 2; i++ { // the Completion Dispatcher
c := <-completions
c.handler(c.name, c.size)
}
}
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: idiom. A goroutine is the processor, and channels are the request queue and the completion queue.
use std::collections::HashMap;
use std::sync::mpsc;
use std::thread;
type Handler = fn(&str, usize);
fn on_read(name: &str, size: usize) {
println!("{} done: {} bytes", name, size);
}
fn main() {
let files: HashMap<&str, &str> = HashMap::from([("a.txt", "hello"), ("b.txt", "abc")]);
let (op_tx, op_rx) = mpsc::channel::<(&'static str, Handler)>();
let (done_tx, done_rx) = mpsc::channel::<(Handler, &'static str, usize)>();
let processor = thread::spawn(move || {
for (name, handler) in op_rx {
done_tx.send((handler, name, files[name].len())).unwrap();
}
});
for name in ["a.txt", "b.txt"] {
println!("start read {}", name);
op_tx.send((name, on_read)).unwrap();
}
drop(op_tx);
for (handler, name, size) in done_rx {
handler(name, size); // the Completion Dispatcher
}
processor.join().unwrap();
}
start read a.txt
start read b.txt
a.txt done: 5 bytes
b.txt done: 3 bytes
- Verdict: stdlib.
std::sync::mpscchannels join the threads, and the loop over the completion channel ends when the processor drops its sender.
Consequences
Benefits:1
- Separation of concerns. The Proactor pattern decouples application-independent asynchrony mechanisms from application-specific functionality.1
- Portability. It improves application portability by allowing its interface to be reused independently of the underlying OS calls that perform event demultiplexing.1
- Simpler synchronization. As long as Completion Handlers do not spawn additional threads of control, application logic can be written with little or no regard to synchronization issues.1
Drawbacks:
- Hard to debug. The inverted flow of control oscillates between the framework infrastructure and the method callbacks on application-specific handlers.1
- Little control of order. Proactive Initiators may have no control over the order in which Asynchronous Operations are executed.1
- Memory use. Buffer space must be committed for the duration of a read or write operation, and a separate buffer is required for each concurrent operation.3
The last drawback is a common mistake. Here two reads share one buffer. The second read writes over the first one before its handler runs:
This code runs but gives a wrong answer on purpose.
files = {"a.txt": b"hello", "b.txt": b"abc"}
completions = []
def start_read(name, buffer, handler):
data = files[name]
buffer[: len(data)] = data # the processor fills the caller's buffer
completions.append((handler, name, len(data)))
def show(name, size):
print(name, "got", bytes(buffer[:size]))
buffer = bytearray(5)
start_read("a.txt", buffer, show)
start_read("b.txt", buffer, show) # same buffer while a.txt is not handled
for handler, name, size in completions:
handler(name, size)
a.txt got b'abclo'
b.txt got b'abc'
The fix is one buffer for each operation that is in progress.3
When not to use it
- The platform has no asynchronous I/O, and a Reactor or blocking threads are simpler.
- The program does few operations at a time. The separation in time and space between operation initiation and completion makes the code more difficult to develop.3
- Memory for buffers is small, and many connections are idle. The Reactor pattern does not require buffer space until a socket is ready for reading or writing.3
Variants and related patterns
- Proactor on top of a Reactor. On many platforms, Boost.Asio implements the Proactor design pattern in terms of a Reactor, such as select, epoll or kqueue.3
- Asynchronous Completion Token. The paper uses it to simplify the asynchronous application programming model: the token tells the handler which request finished.1
- Event handling patterns. POSA2 puts Proactor with Reactor, Asynchronous Completion Token and Acceptor-Connector.4
- Executors and an event loop. In Python,
loop.run_in_executorwill arrange for func to be called in the specified executor.5 The coroutine that waits for the result resumes in the thread of the event loop, which acts as the completion dispatcher:
import asyncio
import threading
def read_file(name): # the asynchronous operation, run in a pool thread
return name, threading.current_thread() is not threading.main_thread()
async def main():
loop = asyncio.get_running_loop()
name, in_pool = await loop.run_in_executor(None, read_file, "a.txt")
print("operation ran in a pool thread:", in_pool)
print("handler runs in the loop thread:", threading.current_thread() is threading.main_thread())
print("result:", name)
asyncio.run(main())
operation ran in a pool thread: True
handler runs in the loop thread: True
result: a.txt
Known uses
- Boost.Asio. Its asynchronous support is based on the Proactor design pattern.3 On Windows it takes advantage of overlapped I/O to provide an efficient implementation of the Proactor design pattern.3
- ACE. The Adaptive Communication Environment is a C++ implementation.2
- Python asyncio.
ProactorEventLoopis a subclass ofAbstractEventLoopfor Windows that uses "I/O Completion Ports" (IOCP).5 - Linux io_uring. io_uring is a Linux-specific API for asynchronous I/O. It allows the user to submit one or more I/O requests, which are processed asynchronously without blocking the calling process.6
References
- Irfan Pyarali, Tim Harrison, Douglas C. Schmidt and Thomas D. Jordan, Proactor, An Object Behavioral Pattern for Demultiplexing and Dispatching Handlers for Asynchronous Events, Intent; Structure; Consequences
- Proactor pattern, Wikipedia, Introduction; Implementations
- The Proactor Design Pattern, Concurrency Without Threads, Boost.Asio 1.86.0 documentation, Implementation Using Reactor; Implementation Using Windows Overlapped I/O; Advantages; Disadvantages
- Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Table of Contents, 3 Event Handling Patterns
- Event Loop, asyncio, Python documentation, loop.run_in_executor; asyncio.ProactorEventLoop
- io_uring(7), Linux manual page, 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 | W4 complete |
|
Tag QGN129 Edit this page History Report an error Markdown