Patterncore
Concurrent pipeline
Also called pipeline, concurrent pipeline, pipeline pattern, staged pipeline, fan-out fan-in.
A concurrent pipeline is a chain of stages that run at the same time and pass values through channels. A slow stage can have several workers, and full buffers make fast stages wait.
- Family
- concurrency
- Intent
- Split the processing of a stream into stages that run concurrently, connect each stage to the next with a channel, and let each stage start on a value as soon as the stage before it sends that value.
- Also called
- Pipes and filters, Fan-out and fan-in
Intent
In software engineering, a pipeline consists of a chain of processing elements, arranged so that the output of each element is the input of the next.1 In a concurrent pipeline, each element is a stage that runs at the same time as the others. In Go terms, a pipeline is a series of stages connected by channels, where each stage is a group of goroutines running the same function.2
Problem
A program reads a stream of values and does several steps of work on each one, for example parse, compute and store. A single loop that does all the steps for one value before it reads the next value uses one processor, and it waits for input and output one value at a time. The steps are independent for different values, so the program could work on several values at once, but threads that share the values need a safe way to pass them on.
Solution
Give each step its own stage, and connect the stages with channels or blocking queues. In each stage, the workers receive values from upstream via inbound channels, perform some function on that data, and send values downstream via outbound channels.2 The first stage is sometimes called the source or producer, and the last stage the sink or consumer.2
source ──► [buf 1] ──┬─► square worker 1 ─┐
1..20 ├─► square worker 2 ─┼─► [buf 1] ──► sink: count, sum
└─► square worker 3 ─┘
fan-out fan-in
A slow stage can have several workers. Multiple functions can read from the same channel until that channel is closed, which is called fan-out.2 A function can read from multiple inputs and proceed until all are closed, by multiplexing the input channels onto a single channel, which is called fan-in.2
The end of the stream must travel through the pipeline. In Go, stages close their outbound channels when all the send operations are done, and they keep receiving values from inbound channels until those channels are closed.2 Usually some amount of buffering is provided between consecutive elements.1 A bounded buffer gives backpressure: in Python, insertion into a Queue with a maxsize will block once this size has been reached, until queue items are consumed.3
Example
A source sends the numbers 1 to 20. Three square workers read from one queue, and they send their results to one output queue. The sink counts the values and adds them up. Each queue holds one value. The source, the workers and the output queue together hold at most five values that the sink has not received, so the source cannot send its last value until the sink has started. The last line shows that the stages ran at the same time.
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
The examples for each language show the same program.
import queue
import threading
ITEMS = 20
WORKERS = 3
DONE = object() # tells the next stage that no more values come
numbers = queue.Queue(maxsize=1) # source -> square workers
squares = queue.Queue(maxsize=1) # square workers -> sink
sink_started = threading.Event()
overlap = []
def source():
for n in range(1, ITEMS + 1):
numbers.put(n, timeout=5) # blocks while the buffer is full
# Each stage can hold only a few values, so the sink must already be running.
overlap.append(sink_started.is_set())
for _ in range(WORKERS):
numbers.put(DONE, timeout=5)
def square():
while (n := numbers.get(timeout=5)) is not DONE:
squares.put(n * n, timeout=5)
squares.put(DONE, timeout=5) # this worker is done
stages = [threading.Thread(target=source)]
stages += [threading.Thread(target=square) for _ in range(WORKERS)] # fan-out
for t in stages:
t.start()
# The sink reads the outputs of all workers from one queue: fan-in.
received, total, finished = 0, 0, 0
while finished < WORKERS:
value = squares.get(timeout=5)
sink_started.set()
if value is DONE:
finished += 1
else:
received += 1
total += value
for t in stages:
t.join()
print("items from the source:", ITEMS)
print("square workers:", WORKERS)
print("squares that reached the sink:", received)
print("sum of squares:", total)
print("the sink got a value before the source sent its last:", overlap[0])
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: stdlib.
queue.Queue(maxsize=1)links the stages, and aDONEmarker per worker ends the stream.
#include <atomic>
#include <condition_variable>
#include <deque>
#include <iostream>
#include <mutex>
#include <optional>
#include <thread>
#include <vector>
// A bounded channel: send waits while the buffer is full, and close ends the stream.
template <typename T>
class Channel {
public:
explicit Channel(size_t capacity) : capacity_(capacity) {}
void send(T v) {
std::unique_lock<std::mutex> lock(m_);
cv_.wait(lock, [&] { return buf_.size() < capacity_; });
buf_.push_back(v);
cv_.notify_all();
}
std::optional<T> receive() { // empty once the channel is closed and drained
std::unique_lock<std::mutex> lock(m_);
cv_.wait(lock, [&] { return !buf_.empty() || closed_; });
if (buf_.empty()) return std::nullopt;
T v = buf_.front();
buf_.pop_front();
cv_.notify_all();
return v;
}
void close() {
std::lock_guard<std::mutex> lock(m_);
closed_ = true;
cv_.notify_all();
}
private:
std::mutex m_;
std::condition_variable cv_;
std::deque<T> buf_;
size_t capacity_;
bool closed_ = false;
};
constexpr int kItems = 20;
constexpr int kWorkers = 3;
int main() {
Channel<int> numbers(1); // source -> square workers
Channel<int> squares(1); // square workers -> sink
std::atomic<bool> sink_started{false};
bool overlap = false;
std::thread source([&] {
for (int n = 1; n <= kItems; n++) numbers.send(n);
// Each stage can hold only a few values, so the sink must already be running.
overlap = sink_started.load();
numbers.close();
});
std::atomic<int> running{kWorkers};
std::vector<std::thread> workers; // fan-out
for (int w = 0; w < kWorkers; w++) {
workers.emplace_back([&] {
while (auto n = numbers.receive()) squares.send(*n * *n);
if (--running == 0) squares.close(); // the last worker closes the output: fan-in
});
}
int received = 0, total = 0;
while (auto v = squares.receive()) {
sink_started = true;
received++;
total += *v;
}
source.join();
for (auto& t : workers) t.join();
std::cout << "items from the source: " << kItems << "\n";
std::cout << "square workers: " << kWorkers << "\n";
std::cout << "squares that reached the sink: " << received << "\n";
std::cout << "sum of squares: " << total << "\n";
std::cout << "the sink got a value before the source sent its last: " << (overlap ? "True" : "False") << "\n";
}
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: idiom. The standard library has no channel, so the example has a small bounded channel class with
close, built onstd::mutexandstd::condition_variable.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
public class Main {
static final int ITEMS = 20;
static final int WORKERS = 3;
static final int DONE = -1; // tells the next stage that no more values come
public static void main(String[] args) throws Exception {
BlockingQueue<Integer> numbers = new ArrayBlockingQueue<>(1); // source -> square workers
BlockingQueue<Integer> squares = new ArrayBlockingQueue<>(1); // square workers -> sink
AtomicBoolean sinkStarted = new AtomicBoolean(false);
boolean[] overlap = new boolean[1];
List<Thread> stages = new ArrayList<>();
stages.add(new Thread(() -> {
try {
for (int n = 1; n <= ITEMS; n++) numbers.put(n); // blocks while the buffer is full
// Each stage can hold only a few values, so the sink must already be running.
overlap[0] = sinkStarted.get();
for (int w = 0; w < WORKERS; w++) numbers.put(DONE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
for (int w = 0; w < WORKERS; w++) { // fan-out
stages.add(new Thread(() -> {
try {
int n;
while ((n = numbers.take()) != DONE) squares.put(n * n);
squares.put(DONE); // this worker is done
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}
for (Thread t : stages) t.start();
// The sink reads the outputs of all workers from one queue: fan-in.
int received = 0, total = 0, finished = 0;
while (finished < WORKERS) {
int value = squares.take();
sinkStarted.set(true);
if (value == DONE) {
finished++;
} else {
received++;
total += value;
}
}
for (Thread t : stages) t.join();
System.out.println("items from the source: " + ITEMS);
System.out.println("square workers: " + WORKERS);
System.out.println("squares that reached the sink: " + received);
System.out.println("sum of squares: " + total);
System.out.println("the sink got a value before the source sent its last: " + (overlap[0] ? "True" : "False"));
}
}
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: stdlib.
ArrayBlockingQueuewith a capacity of 1 links the stages, and aDONEvalue per worker ends the stream.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Channels;
using System.Threading.Tasks;
class Program
{
const int Items = 20;
const int Workers = 3;
static async Task Main()
{
// Bounded channels: a writer waits while the buffer is full.
var numbers = Channel.CreateBounded<int>(1); // source -> square workers
var squares = Channel.CreateBounded<int>(1); // square workers -> sink
int sinkStarted = 0;
bool overlap = false;
var source = Task.Run(async () =>
{
for (int n = 1; n <= Items; n++) await numbers.Writer.WriteAsync(n);
// Each stage can hold only a few values, so the sink must already be running.
overlap = Volatile.Read(ref sinkStarted) == 1;
numbers.Writer.Complete();
});
var workers = Enumerable.Range(0, Workers).Select(_ => Task.Run(async () => // fan-out
{
await foreach (int n in numbers.Reader.ReadAllAsync()) await squares.Writer.WriteAsync(n * n);
})).ToArray();
// The channel closes when all workers are done: fan-in.
var closer = Task.WhenAll(workers).ContinueWith(_ => squares.Writer.Complete());
int received = 0, total = 0;
await foreach (int value in squares.Reader.ReadAllAsync())
{
Volatile.Write(ref sinkStarted, 1);
received++;
total += value;
}
await Task.WhenAll(source, closer);
Console.WriteLine("items from the source: " + Items);
Console.WriteLine("square workers: " + Workers);
Console.WriteLine("squares that reached the sink: " + received);
Console.WriteLine("sum of squares: " + total);
Console.WriteLine("the sink got a value before the source sent its last: " + (overlap ? "True" : "False"));
}
}
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: stdlib.
System.Threading.ChannelswithChannel.CreateBounded,ReadAllAsyncandWriter.Complete()to close a stage.
// A bounded channel for async tasks: send waits while the buffer is full.
class Channel {
constructor(capacity) {
this.capacity = capacity;
this.buf = [];
this.closed = false;
this.waiters = []; // tasks that wait for a change
}
wake() {
const w = this.waiters;
this.waiters = [];
w.forEach((r) => r());
}
async send(v) {
while (this.buf.length >= this.capacity) await new Promise((r) => this.waiters.push(r));
this.buf.push(v);
this.wake();
}
async receive() {
// Returns undefined once the channel is closed and drained.
while (this.buf.length === 0 && !this.closed) await new Promise((r) => this.waiters.push(r));
if (this.buf.length === 0) return undefined;
const v = this.buf.shift();
this.wake();
return v;
}
close() {
this.closed = true;
this.wake();
}
}
const ITEMS = 20;
const WORKERS = 3;
const numbers = new Channel(1); // source -> square workers
const squares = new Channel(1); // square workers -> sink
let sinkStarted = false;
let overlap = false;
async function source() {
for (let n = 1; n <= ITEMS; n++) await numbers.send(n);
// Each stage can hold only a few values, so the sink must already be running.
overlap = sinkStarted;
numbers.close();
}
async function square() {
let n;
while ((n = await numbers.receive()) !== undefined) await squares.send(n * n);
}
async function main() {
const stages = [source()];
const workers = Array.from({ length: WORKERS }, () => square()); // fan-out
// The output closes when all workers are done: fan-in.
stages.push(Promise.all(workers).then(() => squares.close()));
let received = 0;
let total = 0;
let v;
while ((v = await squares.receive()) !== undefined) {
sinkStarted = true;
received++;
total += v;
}
await Promise.all(stages);
console.log("items from the source:", ITEMS);
console.log("square workers:", WORKERS);
console.log("squares that reached the sink:", received);
console.log("sum of squares:", total);
console.log("the sink got a value before the source sent its last:", overlap ? "True" : "False");
}
main();
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: idiom. A small bounded channel class for async tasks on one event loop. It shows the stages and the backpressure, not parallel work.
// A bounded channel for async tasks: send waits while the buffer is full.
class Channel<T> {
capacity: number;
buf: T[];
closed: boolean;
waiters: (() => void)[];
constructor(capacity: number) {
this.capacity = capacity;
this.buf = [];
this.closed = false;
this.waiters = []; // tasks that wait for a change
}
wake(): void {
const w = this.waiters;
this.waiters = [];
w.forEach((r) => r());
}
async send(v: T): Promise<void> {
while (this.buf.length >= this.capacity) await new Promise<void>((r) => this.waiters.push(r));
this.buf.push(v);
this.wake();
}
async receive(): Promise<T | undefined> {
// Returns undefined once the channel is closed and drained.
while (this.buf.length === 0 && !this.closed) await new Promise<void>((r) => this.waiters.push(r));
if (this.buf.length === 0) return undefined;
const v = this.buf.shift();
this.wake();
return v;
}
close(): void {
this.closed = true;
this.wake();
}
}
const ITEMS = 20;
const WORKERS = 3;
const numbers = new Channel<number>(1); // source -> square workers
const squares = new Channel<number>(1); // square workers -> sink
let sinkStarted = false;
let overlap = false;
async function source(): Promise<void> {
for (let n = 1; n <= ITEMS; n++) await numbers.send(n);
// Each stage can hold only a few values, so the sink must already be running.
overlap = sinkStarted;
numbers.close();
}
async function square(): Promise<void> {
let n: number | undefined;
while ((n = await numbers.receive()) !== undefined) await squares.send(n * n);
}
async function main(): Promise<void> {
const stages: Promise<void>[] = [source()];
const workers = Array.from({ length: WORKERS }, () => square()); // fan-out
// The output closes when all workers are done: fan-in.
stages.push(Promise.all(workers).then(() => squares.close()));
let received = 0;
let total = 0;
let v: number | undefined;
while ((v = await squares.receive()) !== undefined) {
sinkStarted = true;
received++;
total += v;
}
await Promise.all(stages);
console.log("items from the source:", ITEMS);
console.log("square workers:", WORKERS);
console.log("squares that reached the sink:", received);
console.log("sum of squares:", total);
console.log("the sink got a value before the source sent its last:", overlap ? "True" : "False");
}
main();
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: idiom. A small generic
Channel<T>class for async tasks on one event loop. It shows the stages and the backpressure, not parallel work.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
const (
items = 20
workers = 3
)
var sinkStarted atomic.Bool
// source sends the numbers and closes its channel when it is done.
func source(overlap *bool) <-chan int {
out := make(chan int, 1) // blocks while the buffer is full
go func() {
for n := 1; n <= items; n++ {
out <- n
}
// Each stage can hold only a few values, so the sink must already be running.
*overlap = sinkStarted.Load()
close(out)
}()
return out
}
// square starts the workers on one input channel (fan-out). They send to one
// output channel, which is closed when all workers are done (fan-in).
func square(in <-chan int) <-chan int {
out := make(chan int, 1)
var wg sync.WaitGroup
for w := 0; w < workers; w++ {
wg.Add(1)
go func() {
defer wg.Done()
for n := range in {
out <- n * n
}
}()
}
go func() {
wg.Wait()
close(out)
}()
return out
}
func main() {
var overlap bool
squares := square(source(&overlap))
received, total := 0, 0
for v := range squares {
sinkStarted.Store(true)
received++
total += v
}
fmt.Println("items from the source:", items)
fmt.Println("square workers:", workers)
fmt.Println("squares that reached the sink:", received)
fmt.Println("sum of squares:", total)
fmt.Println("the sink got a value before the source sent its last:", map[bool]string{true: "True", false: "False"}[overlap])
}
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: native. Buffered channels link the stages,
rangereads until a channel is closed, and async.WaitGroupcloses the output when all workers are done.
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::sync_channel;
use std::sync::{Arc, Mutex};
use std::thread;
const ITEMS: i64 = 20;
const WORKERS: usize = 3;
fn main() {
// Bounded channels: a send waits while the buffer is full.
let (numbers_tx, numbers_rx) = sync_channel::<i64>(1); // source -> square workers
let (squares_tx, squares_rx) = sync_channel::<i64>(1); // square workers -> sink
let sink_started = Arc::new(AtomicBool::new(false));
let started = Arc::clone(&sink_started);
let source = thread::spawn(move || {
for n in 1..=ITEMS {
numbers_tx.send(n).unwrap();
}
// Each stage can hold only a few values, so the sink must already be running.
started.load(Ordering::SeqCst)
// numbers_tx is dropped here, which closes the channel
});
// The workers share one receiver (fan-out) and each owns a sender to the sink (fan-in).
let numbers_rx = Arc::new(Mutex::new(numbers_rx));
let workers: Vec<_> = (0..WORKERS)
.map(|_| {
let (rx, tx) = (Arc::clone(&numbers_rx), squares_tx.clone());
thread::spawn(move || loop {
let next = rx.lock().unwrap().recv();
match next {
Ok(n) => tx.send(n * n).unwrap(),
Err(_) => break, // the source is done
}
})
})
.collect();
drop(squares_tx); // the channel closes when the last worker drops its sender
let (mut received, mut total) = (0, 0);
for v in squares_rx {
sink_started.store(true, Ordering::SeqCst);
received += 1;
total += v;
}
let overlap = source.join().unwrap();
for w in workers {
w.join().unwrap();
}
println!("items from the source: {}", ITEMS);
println!("square workers: {}", WORKERS);
println!("squares that reached the sink: {}", received);
println!("sum of squares: {}", total);
println!("the sink got a value before the source sent its last: {}", if overlap { "True" } else { "False" });
}
items from the source: 20
square workers: 3
squares that reached the sink: 20
sum of squares: 2870
the sink got a value before the source sent its last: True
- Verdict: stdlib.
std::sync::mpsc::sync_channel(1)links the stages. The workers share the receiver behind aMutex, and dropping the senders closes each channel.
Consequences
Benefits:
- The stages run at the same time on different values. Go's concurrency primitives make it easy to construct streaming data pipelines that make efficient use of I/O and multiple CPUs.2
- Each stage is small and has one job. Connecting elements into a pipeline is analogous to function composition.1
- Fan-out gives a slow stage more workers without a change to the other stages, as a way to distribute work amongst a group of workers to parallelize CPU use and I/O.2
- Bounded buffers limit the memory that the pipeline uses, because a fast stage waits for a slow one.
Liabilities:
- The pipeline is as fast as its slowest stage, unless that stage has enough workers.
- Fan-out changes the order of the values. In the example, the sink adds the values, so the order does not matter. A sink that needs the order must sort the values again.
- A stage that stops early can leave the stages before it blocked. In Go, this is a resource leak: goroutines consume memory and runtime resources, and goroutines are not garbage collected; they must exit on their own.2
In this program, the sink stops after three values and does not tell the source:
This code runs but gives a wrong answer on purpose.
import queue
import threading
numbers = queue.Queue(maxsize=1)
stuck = []
def source():
for n in range(1, 21):
try:
numbers.put(n, timeout=0.5)
except queue.Full:
stuck.append(n) # nobody will ever receive this value
return
producer = threading.Thread(target=source)
producer.start()
# Wrong: the sink stops after 3 values and does not tell the source.
used = [numbers.get() for _ in range(3)]
producer.join()
print("values the sink used:", used)
print("source stuck on a send that nobody receives:", len(stuck) == 1)
values the sink used: [1, 2, 3]
source stuck on a send that nobody receives: True
The source ends here only because its put has a timeout. Without a timeout, the source thread would wait forever for a free slot.
When not to use it
Do not use a pipeline when the work is one step. A thread pool or a producer-consumer queue is simpler. Do not split cheap steps into stages, because each pass through a channel costs a lock and a thread switch. Do not use a pipeline for work that is not a stream, such as one large computation that splits into parts and joins them. Fork-join fits that case.
Variants and related patterns
- Explicit cancellation. When the sink decides to stop early, it must tell the upstream stages to abandon the values they are trying to send.2 In Go, closing a
donechannel is effectively a broadcast signal to the senders.2 Python'sQueue.shutdown()puts a queue into a shutdown mode, and currently blocked callers ofput()will be unblocked and will raiseShutDown.3 This program uses an event as thedonesignal:
import queue
import threading
numbers = queue.Queue(maxsize=1)
done = threading.Event() # the sink sets it to cancel the upstream stage
sent = []
def source():
for n in range(1, 21):
while not done.is_set():
try:
numbers.put(n, timeout=0.05)
sent.append(n)
break
except queue.Full:
pass # check done again, then try again
if done.is_set():
return
producer = threading.Thread(target=source)
producer.start()
used = [numbers.get() for _ in range(3)]
done.set() # tell the source to stop
producer.join(timeout=5)
print("values the sink used:", used)
print("source finished:", not producer.is_alive())
print("source stopped before it sent all 20:", len(sent) < 20)
values the sink used: [1, 2, 3]
source finished: True
source stopped before it sent all 20: True
- Close by dropping the sender. In Rust, an unsuccessful send or receive is normally indicative of the other half of a channel having hung up by being dropped.4 A stage ends when its sender is dropped, and the Rust example uses this as the close signal.
- Bounded or unbounded links. A Rust
sync_channelhas a pre-allocated buffer of a fixed size, and all sends block until there is buffer space available, while achannelconceptually has an infinite buffer.4
Each link of the pipeline is a producer-consumer queue. The stages communicate by message passing over channels, not by shared variables. The Replace loop with pipeline refactoring builds a pipeline of collection operations in one thread. This page is about stages that run concurrently.
Known uses
- Go pipelines of goroutines and channels, with fan-out, fan-in and a
donechannel for cancellation.2 - Python
queue.Queuewith amaxsizebetween threads.3 - Rust
std::sync::mpscchannels, which are multi-producer, single-consumer FIFO queues.4 - The pipe(s) and filters design pattern, in which the elements of a pipeline may be called filters.1
References
- Pipeline (software), Wikipedia, lead
- Sameer Ajmani, Go Concurrency Patterns, Pipelines and cancellation, The Go Blog (13 March 2014), What is a pipeline?; Fan-out, fan-in; Stopping short; Explicit cancellation
- queue, A synchronized queue class, Python documentation, the module description; Queue; Queue.put; Queue.shutdown
- The Rust Standard Library, module std::sync::mpsc, the module description; Disconnection
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 0M24GG Edit this page History Report an error Markdown