Programming Search⌘K

Conceptcore

Channel

Also called CSP channel, message channel.

A channel is a typed conduit between concurrent processes. One process sends a value into it and another receives the value, so the two exchange data and synchronize without shared variables.

Applies to
core-languages

Idea

Concurrent processes must exchange data. One way is to share variables and protect them with locks (see Mutual exclusion). A channel is the other way. A channel is a conduit that carries values of one type from one process to another. A process sends a value into the channel, and another process receives it. The send and the receive also synchronize the two processes, so the receiver sees the value only after the sender has made it.

Hoare described this model in 1978 as communicating sequential processes, or CSP. In his proposal, processes do not communicate by updating global variables. They communicate only through input and output commands. An output command in one process and an input command in another process meet, and the value is copied from the first process to the second.1 The Go documentation states the same idea as a slogan: "Do not communicate by sharing memory; instead, share memory by communicating."2 Only one process owns a value at a time, so two processes cannot race on it (see Data race).

In Go, make(chan int) makes a channel, ch <- v sends and <-ch receives.4 In the example, the main goroutine waits at the receive until the other goroutine sends.

package main

import "fmt"

func main() {
	results := make(chan string)
	go func() {
		results <- "hello from a goroutine"
	}()
	fmt.Println(<-results)
}
Output
hello from a goroutine

The function literal that starts the goroutine is a closure over results (see Closure). A channel is a value, so a function can take it as a parameter, return it, or send it on another channel.3

How it works

Send, receive and the buffer

A channel has a capacity. If the capacity is zero, the channel is unbuffered. A send and a receive on it succeed only when both a sender and a receiver are ready.4 The two processes meet at that point, which is a rendezvous. If the capacity is greater than zero, the channel holds a buffer. A send does not block while the buffer has room, and a receive does not block while the buffer holds a value. In both cases the channel is a first-in, first-out queue.4

Hoare's processes had no buffer: a command waited until the other process was ready.1 He discussed automatic buffering and set it aside, because a buffer can be built from the primitives. His own example is a bounded buffer: a process that holds ten portions and runs between a producer and a consumer.1 Most channel libraries offer both forms.

Capacity Send blocks when Receive blocks when Use
0 (rendezvous) no receiver is ready no sender is ready hand over a value and synchronize at the same time
n > 0 (bounded) the buffer holds n values the buffer is empty smooth out bursts; limit work in progress
no limit (unbounded) never the buffer is empty decouple producers from a slow consumer, at the cost of memory

A bounded channel gives back pressure. When the consumer is slow, the buffer fills and the producers wait. The .NET documentation uses this term for a writer that produces faster than the reader consumes.18 An unbounded channel never makes the producer wait, so its memory can grow without limit. Rust calls its unbounded channel() asynchronous, with a buffer that is "conceptually infinite".13

Synchronization and memory

A channel operation is also a memory barrier between the two processes. The Go memory model states that a send is synchronized before the completion of the matching receive. For an unbuffered channel, the receive is also synchronized before the completion of the send.10 Java gives the same guarantee for a BlockingQueue: the actions of a thread before it puts an object into the queue happen before the actions after another thread takes it.17 So the receiver can read the fields of a received object without a lock, as long as the sender does not change the object after the send.

The memory model has one more rule. On a channel with capacity C, the kth receive is synchronized before the completion of the (k+C)th send.10 So a buffered channel of capacity C can limit the number of active workers to C. Each worker sends before it starts and receives when it finishes. This is the counting semaphore idiom.3

Close

A sender can close a channel to say that no more values will come. In Go, a receive on a closed channel proceeds at once. It first yields the values that were sent before the close, and after that the zero value of the element type.6 The two-value form v, ok := <-ch tells the two cases apart: ok is false when the value comes from a closed, empty channel.6 A for v := range ch loop receives values until the channel is closed.9 A close is synchronized before a receive that returns because the channel is closed.10

Close is a message from the sender side. A send on a closed channel causes a run-time panic, and so does a second close.57 So the rule is: the sender closes, never the receiver. With several senders, the channel is closed only after all of them have finished (see Pitfalls).

Other libraries signal the end in other ways:

Library End of stream
Go close(ch); then v, ok gives ok == false6
Rust mpsc no close; the channel hangs up when all senders are dropped, and recv returns Err13
.NET Channel<T> Writer.Complete(); a later write throws ChannelClosedException18
.NET BlockingCollection<T> CompleteAdding(); GetConsumingEnumerable() ends19
Kotlin kotlinx.coroutines close(), which acts like a special close token22
Java BlockingQueue no close; the producer sends a "poison" object17
Python queue.Queue a sentinel object that the consumer recognizes20

The Rust rule fits ownership. Each producer holds a clone of the Sender. When the last clone is dropped, the receiver iterator ends.14 In the Rust example, the main thread drops its own sender before it reads, or the loop would never end.

Select

A process often waits on more than one channel: a result channel, a cancel channel and a timer. Hoare allowed input commands in guards. When several guards are ready, the choice between them is arbitrary.1 Go has the select statement. If one or more of its cases can proceed, it picks one by a uniform pseudo-random choice. If none can proceed, it runs the default case if there is one; otherwise it blocks.8 A default case gives a send or receive that does not block. A case that receives from time.After gives a timeout, as in the Go example.

A nil channel is never ready. A send or a receive on it blocks forever.456 Inside a select, this is useful. A loop that sets a channel variable to nil turns off that case. Here the loop merges two channels and stops when both are closed.

package main

import "fmt"

func numbers(from, to int) <-chan int {
	ch := make(chan int)
	go func() {
		for i := from; i <= to; i++ {
			ch <- i
		}
		close(ch)
	}()
	return ch
}

func main() {
	a, b := numbers(1, 3), numbers(10, 12)
	sum := 0
	for a != nil || b != nil {
		select {
		case v, ok := <-a:
			if !ok {
				a = nil // a is closed: turn off this case
				continue
			}
			sum += v
		case v, ok := <-b:
			if !ok {
				b = nil
				continue
			}
			sum += v
		}
	}
	fmt.Println("sum:", sum)
}
Output
sum: 39

The order in which select takes the values changes from run to run, so the program prints only the sum. The return type <-chan int is a receive-only channel. The compiler rejects a send or a close on it.47

Most libraries have no general select. Rust mpsc has recv_timeout and try_recv on one receiver.14 Java has poll with a time limit.17 .NET BlockingCollection<T> has TakeFromAny, which takes an item from any one of several collections.19

Producers and consumers

The common shape has several producers, one channel and one or more consumers. Fan-out means several consumers take from one channel, so the work spreads over them. Fan-in means several producers send to one channel, so one consumer sees all results. Every example file shows fan-in: two producers each send three values, and one consumer adds them. The order of arrival changes from run to run, but the total does not.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaStandard library
CIdiom
C#Standard library
JavaScriptStandard library
TypeScriptStandard library
GoNative
RustStandard library
KotlinLibrary
SQLDoes not applyA query has no concurrent processes that exchange values.
BashAbsentBash has no channel values. A pipeline connects the standard output of one process to the standard input of the next, so it carries bytes, not typed values. Alternative: A pipeline of processes, or a named pipe made by the POSIX mkfifo utility that unrelated processes open.
PowerShellStandard library
HTMLDoes not applyMarkup has no processes.
CSSDoes not applyStyle rules have no processes.
Regular expressionsDoes not applyA pattern has no processes.
Language Verdict Form
Go native chan T, <-, close, select, range
Rust stdlib std::sync::mpsc::channel and sync_channel; multi-producer, single consumer
Java stdlib BlockingQueue (ArrayBlockingQueue, LinkedBlockingQueue) and SynchronousQueue
C# stdlib System.Threading.Channels.Channel<T> (asynchronous); BlockingCollection<T> (blocking)
PowerShell stdlib the .NET BlockingCollection<T> with ForEach-Object -Parallel or thread jobs
Python stdlib queue.Queue for threads
JavaScript stdlib MessageChannel and postMessage between worker threads in Node.js
TypeScript stdlib as JavaScript
Kotlin library Channel from kotlinx.coroutines; the JDK queues with the standard library only
C++ idiom a queue with std::mutex and std::condition_variable
C idiom a queue with pthread_mutex_t and pthread_cond_t
Bash absent a pipeline of processes, or a named pipe made by mkfifo
SQL n/a a query has no processes
Regex n/a a pattern has no processes
HTML/CSS n/a markup and style rules have no processes

Go is the only tier 1 language with channels in the language itself. Its documentation traces this design to CSP, and names Newsqueak and Limbo as the languages that its concurrency ideas come from.1112

Rust's mpsc module gives a Sender that can be cloned and one Receiver, so several producers can feed one consumer.13 sync_channel(0) makes a rendezvous channel.13 A multi-consumer module, std::sync::mpmc, exists only as a nightly-only experimental API.15

Java's SynchronousQueue has no internal capacity, not even a capacity of one. Each insert waits for a remove. Its documentation compares it with the rendezvous channels of CSP and Ada.16 A BlockingQueue has no close or shutdown operation, so the usual end signal is a poison object that the consumer recognizes.17 Kotlin on the JVM can use the same queues. The idiomatic Kotlin form is the Channel of kotlinx.coroutines, a library outside the Kotlin standard library. Its send and receive suspend a coroutine instead of blocking a thread, and its default capacity is a rendezvous.2223

The .NET Channel<T> has an asynchronous writer and reader. A bounded channel needs a capacity greater than zero, so .NET has no rendezvous channel. When the buffer is full, the writer waits by default. Other full modes drop the newest item, drop the oldest item, or drop the item being written.18 The older BlockingCollection<T> blocks the calling thread instead.19 PowerShell uses it directly, because a script can call any .NET class.

Python's queue.Queue is a multi-producer, multi-consumer queue that does its own locking. A maxsize of zero or less makes the queue unbounded. task_done and join let a producer wait until consumers have processed every item.20 Programs that use coroutines take asyncio.Queue instead (see Async/await).

In Node.js, each worker thread has its own event loop. A MessageChannel is an asynchronous, two-way channel with two ports. postMessage copies its value with the HTML structured clone algorithm, so the receiver never shares the object with the sender.21 A send does not wait for the receiver. receiveMessageOnPort receives one message at once and returns undefined when none waits.21

C and C++ have no channel in their standard libraries. The usual form is a queue that a mutex protects, with one condition variable for "not full" and one for "not empty". A wait on a condition variable can return without a signal (a spurious wakeup), so the code tests the condition again in a loop. The C++ standard and POSIX both allow such wakeups.2425

A Bash pipeline connects the standard output of one command to the standard input of the next.27 It is a channel of bytes between processes. The mkfifo utility makes a named pipe, a FIFO special file, that unrelated processes can open.28 Neither carries typed values.

PythonGitHub
import queue
import threading

DONE = object()  # the sentinel: no real job is this object


def produce(ident, jobs):
    for i in range(1, 4):
        jobs.put(ident * 10 * i)  # blocks while the queue is full
    jobs.put(DONE)


def consume(jobs, results):
    finished = 0
    while finished < 2:
        item = jobs.get()
        if item is DONE:
            finished += 1
        else:
            results.append(item)
        jobs.task_done()


jobs = queue.Queue(maxsize=2)
results = []
threads = [threading.Thread(target=produce, args=(n, jobs)) for n in (1, 2)]
threads.append(threading.Thread(target=consume, args=(jobs, results)))
for t in threads:
    t.start()
jobs.join()  # waits until task_done was called for every item
for t in threads:
    t.join()
print("total:", sum(results))

try:
    jobs.get(timeout=0.05)
except queue.Empty:
    print("timeout")
Output
total: 180
timeout
  • Verdict: stdlib. queue.Queue is a multi-producer, multi-consumer FIFO queue with its own locks. maxsize bounds it; a size of 0 or less means no bound.
  • task_done and join let a producer wait until the consumers have handled every item.
  • The usual end signal is a sentinel object. Programs with coroutines use asyncio.Queue instead (see Async/await).
#include <condition_variable>
#include <deque>
#include <mutex>
#include <optional>
#include <print>
#include <thread>
#include <vector>

template <typename T>
class Channel {
public:
    explicit Channel(std::size_t cap) : cap_(cap) {}
    void send(T v) {
        std::unique_lock lock(m_);
        not_full_.wait(lock, [&] { return q_.size() < cap_; });
        q_.push_back(std::move(v));
        not_empty_.notify_one();
    }
    std::optional<T> receive() { // empty optional: closed and drained
        std::unique_lock lock(m_);
        not_empty_.wait(lock, [&] { return !q_.empty() || closed_; });
        if (q_.empty()) return std::nullopt;
        T v = std::move(q_.front());
        q_.pop_front();
        not_full_.notify_one();
        return v;
    }
    void close() {
        std::lock_guard lock(m_);
        closed_ = true;
        not_empty_.notify_all();
    }

private:
    std::mutex m_;
    std::condition_variable not_full_, not_empty_;
    std::deque<T> q_;
    std::size_t cap_;
    bool closed_ = false;
};

int main() {
    Channel<int> jobs(2);
    std::vector<std::jthread> producers;
    for (int id = 1; id <= 2; ++id) {
        producers.emplace_back([&jobs, id] {
            for (int i = 1; i <= 3; ++i) jobs.send(id * 10 * i);
        });
    }
    std::jthread closer([&] {
        for (auto& p : producers) p.join();
        jobs.close();
    });
    int total = 0;
    while (auto v = jobs.receive()) total += *v;
    std::println("total: {}", total);
}
Output
total: 180
  • Verdict: idiom. The C++ standard library has no channel. A queue guarded by a std::mutex, with one std::condition_variable for "not full" and one for "not empty", is the usual form.
  • wait with a predicate loops until the condition holds, because a wait can also return spuriously.
  • This sketch has no rendezvous and no select; each of those needs more state.
JavaGitHub
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

public class Main {
    static final int DONE = -1; // the poison pill: a value that means "no more"

    public static void main(String[] args) throws InterruptedException {
        BlockingQueue<Integer> jobs = new ArrayBlockingQueue<>(2);
        Thread[] producers = new Thread[2];
        for (int p = 0; p < 2; p++) {
            int id = p + 1;
            producers[p] = Thread.ofPlatform().start(() -> {
                try {
                    for (int i = 1; i <= 3; i++) {
                        jobs.put(id * 10 * i); // blocks while the queue is full
                    }
                    jobs.put(DONE);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            });
        }
        int total = 0;
        int finished = 0;
        while (finished < producers.length) {
            int v = jobs.take();
            if (v == DONE) finished++;
            else total += v;
        }
        for (Thread t : producers) t.join();
        System.out.println("total: " + total);

        SynchronousQueue<String> handoff = new SynchronousQueue<>();
        System.out.println("offer with no taker: " + handoff.offer("x"));
        Thread taker = Thread.ofPlatform().start(() -> {
            try {
                System.out.println("took: " + handoff.take());
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        handoff.put("ping"); // waits for the taker
        taker.join();
        System.out.println("poll: " + jobs.poll(50, TimeUnit.MILLISECONDS));
    }
}
Output
total: 180
offer with no taker: false
took: ping
poll: null
  • Verdict: stdlib. java.util.concurrent.BlockingQueue is the channel. SynchronousQueue has no capacity, so each put waits for a take, as in a rendezvous.
  • A BlockingQueue cannot be closed. The producers send an agreed "poison" value to say that they have finished.
  • The interface has no operation that waits on several queues at once. poll with a time limit gives a receive with a timeout.
#include <pthread.h>
#include <stdbool.h>
#include <stdio.h>

#define CAP 2

typedef struct {
    pthread_mutex_t m;
    pthread_cond_t not_full, not_empty;
    int buf[CAP];
    int head, count;
    bool closed;
} channel;

static void ch_send(channel *c, int v) {
    pthread_mutex_lock(&c->m);
    while (c->count == CAP) pthread_cond_wait(&c->not_full, &c->m);
    c->buf[(c->head + c->count) % CAP] = v;
    c->count++;
    pthread_cond_signal(&c->not_empty);
    pthread_mutex_unlock(&c->m);
}

static bool ch_recv(channel *c, int *out) { /* false: closed and drained */
    pthread_mutex_lock(&c->m);
    while (c->count == 0 && !c->closed) pthread_cond_wait(&c->not_empty, &c->m);
    bool ok = c->count > 0;
    if (ok) {
        *out = c->buf[c->head];
        c->head = (c->head + 1) % CAP;
        c->count--;
        pthread_cond_signal(&c->not_full);
    }
    pthread_mutex_unlock(&c->m);
    return ok;
}

static void ch_close(channel *c) {
    pthread_mutex_lock(&c->m);
    c->closed = true;
    pthread_cond_broadcast(&c->not_empty);
    pthread_mutex_unlock(&c->m);
}

static channel jobs = {PTHREAD_MUTEX_INITIALIZER, PTHREAD_COND_INITIALIZER,
                       PTHREAD_COND_INITIALIZER};

static void *produce(void *arg) {
    int id = *(int *)arg;
    for (int i = 1; i <= 3; i++) ch_send(&jobs, id * 10 * i);
    return NULL;
}

static void *consume(void *arg) {
    int v, *total = arg;
    while (ch_recv(&jobs, &v)) *total += v;
    return NULL;
}

int main(void) {
    pthread_t p[2], c;
    int ids[2] = {1, 2}, total = 0;
    pthread_create(&c, NULL, consume, &total);
    for (int i = 0; i < 2; i++) pthread_create(&p[i], NULL, produce, &ids[i]);
    for (int i = 0; i < 2; i++) pthread_join(p[i], NULL);
    ch_close(&jobs);
    pthread_join(c, NULL);
    printf("total: %d\n", total);
    return 0;
}
Output
total: 180
  • Verdict: idiom. ISO C and POSIX have no channel. A ring buffer guarded by a pthread_mutex_t, with two condition variables, is the usual form.
  • Each pthread_cond_wait sits in a while loop that tests the condition again, because a wait can return spuriously.
  • Pipes (pipe) carry bytes between processes or threads. They are a channel of bytes, not of typed values.
using System.Threading.Channels;

var jobs = Channel.CreateBounded<int>(2); // full mode Wait: WriteAsync waits for room
var producers = Enumerable.Range(1, 2).Select(id => Task.Run(async () =>
{
    for (int i = 1; i <= 3; i++)
    {
        await jobs.Writer.WriteAsync(id * 10 * i);
    }
})).ToArray();
_ = Task.WhenAll(producers).ContinueWith(_ => jobs.Writer.Complete()); // after all producers

int total = 0;
await foreach (int v in jobs.Reader.ReadAllAsync()) // ends after Complete
{
    total += v;
}
Console.WriteLine($"total: {total}");
Console.WriteLine($"TryWrite after Complete: {jobs.Writer.TryWrite(1)}");

try
{
    await jobs.Writer.WriteAsync(1);
}
catch (ChannelClosedException e)
{
    Console.WriteLine(e.GetType().Name);
}

using var limit = new CancellationTokenSource(TimeSpan.FromMilliseconds(50));
var empty = Channel.CreateUnbounded<int>();
try
{
    await empty.Reader.ReadAsync(limit.Token);
}
catch (OperationCanceledException)
{
    Console.WriteLine("timeout");
}
Output
total: 180
TryWrite after Complete: False
ChannelClosedException
timeout
  • Verdict: stdlib. System.Threading.Channels gives Channel<T> with a writer half and a reader half. Its operations are asynchronous: WriteAsync and ReadAsync return a ValueTask.
  • A bounded channel needs a capacity greater than zero, so there is no rendezvous channel.
  • Complete closes the writer. A later write throws ChannelClosedException, and the reader sees the end after the buffered items.
  • BlockingCollection<T> is the older, blocking form: Add, Take, CompleteAdding and GetConsumingEnumerable.
JavaScriptGitHub
import {
  MessageChannel,
  Worker,
  isMainThread,
  receiveMessageOnPort,
  workerData,
} from "node:worker_threads";

if (isMainThread) {
  let total = 0;
  let finished = 0;
  for (const id of [1, 2]) {
    const { port1, port2 } = new MessageChannel();
    new Worker(new URL(import.meta.url), {
      workerData: { id, port: port2 },
      transferList: [port2], // the worker owns port2 now
    });
    port1.on("message", (msg) => {
      if (msg === "done") {
        port1.close();
        finished += 1;
        if (finished === 2) console.log("total:", total);
      } else {
        total += msg.value;
      }
    });
  }

  const { port1, port2 } = new MessageChannel();
  const job = { value: 1 };
  port1.postMessage(job);
  job.value = 2; // changes the sender's object only
  console.log(receiveMessageOnPort(port2));
  console.log(receiveMessageOnPort(port2));
  port1.close();
} else {
  const { id, port } = workerData;
  for (let i = 1; i <= 3; i++) port.postMessage({ value: id * 10 * i });
  port.postMessage("done");
}
Output
{ message: { value: 1 } }
undefined
total: 180
  • Verdict: stdlib. The language has no channel. MessageChannel in node:worker_threads gives two connected MessagePort objects, and each worker thread has its own event loop.
  • postMessage is asynchronous: it does not wait for the receiver, so there is no rendezvous. The receiver gets a structured clone of the value, so a later change by the sender does not reach it.
  • close disables further sending on both ports. receiveMessageOnPort receives at once and returns undefined when no message waits.
TypeScriptGitHub
import {
  MessageChannel,
  MessagePort,
  Worker,
  isMainThread,
  receiveMessageOnPort,
  workerData,
} from "node:worker_threads";

type Msg = { value: number } | "done";

if (isMainThread) {
  let total = 0;
  let finished = 0;
  for (const id of [1, 2]) {
    const { port1, port2 } = new MessageChannel();
    new Worker(new URL(import.meta.url), {
      workerData: { id, port: port2 },
      transferList: [port2],
    });
    port1.on("message", (msg: Msg) => {
      if (msg === "done") {
        port1.close();
        finished += 1;
        if (finished === 2) console.log("total:", total);
      } else {
        total += msg.value;
      }
    });
  }
} else {
  const { id, port } = workerData as { id: number; port: MessagePort };
  for (let i = 1; i <= 3; i++) port.postMessage({ value: id * 10 * i } satisfies Msg);
  port.postMessage("done" satisfies Msg);
}
Output
total: 180
  • Verdict: stdlib. TypeScript uses the same Node.js API as JavaScript.
  • The union type Msg covers both the data message and the end marker, and satisfies checks each sent value against it. Nothing checks a received message at run time, so the type in the handler is a promise of the programmer.
package main

import "fmt"

func produce(id int, out chan<- int, done chan<- bool) {
	for i := 1; i <= 3; i++ {
		out <- id * 10 * i
	}
	done <- true
}

func main() {
	jobs := make(chan int, 2) // buffered: capacity 2
	done := make(chan bool)   // unbuffered: a rendezvous
	for id := 1; id <= 2; id++ {
		go produce(id, jobs, done)
	}
	go func() {
		<-done
		<-done
		close(jobs) // both producers have finished
	}()
	total := 0
	for v := range jobs { // ends when jobs is closed and empty
		total += v
	}
	v, ok := <-jobs
	fmt.Println("total:", total)
	fmt.Println("after close:", v, ok)
}
Output
total: 180
after close: 0 false
package main

import (
	"fmt"
	"time"
)

func main() {
	ch := make(chan string, 1) // room for the late value, so the sender never blocks
	select {
	case msg := <-ch:
		fmt.Println("got", msg)
	default:
		fmt.Println("no value ready")
	}
	go func() {
		time.Sleep(500 * time.Millisecond)
		ch <- "late"
	}()
	select {
	case msg := <-ch:
		fmt.Println("got", msg)
	case <-time.After(50 * time.Millisecond):
		fmt.Println("timeout")
	}
}
Output
no value ready
timeout
  • Verdict: native. chan T, the <- operator, close, select and range are part of the language.
  • chan<- int is a send-only type. The compiler rejects a receive on it.
  • A receive after close returns at once with the zero value and ok == false.
RustGitHub
use std::sync::mpsc;
use std::thread;
use std::time::Duration;

fn main() {
    let (tx, rx) = mpsc::channel();
    let mut handles = Vec::new();
    for id in 1..=2 {
        let tx = tx.clone(); // one Sender for each producer
        handles.push(thread::spawn(move || {
            for i in 1..=3 {
                tx.send(id * 10 * i).unwrap();
            }
        }));
    }
    drop(tx); // the original Sender
    let total: i32 = rx.iter().sum(); // ends when every Sender is dropped
    for h in handles {
        h.join().unwrap();
    }
    println!("total: {total}");
    println!("after hang-up: {:?}", rx.recv());

    let (tx, rx) = mpsc::sync_channel::<&str>(0); // bound 0: a rendezvous
    let sender = thread::spawn(move || {
        tx.send("ping").unwrap(); // blocks until the receive below
    });
    println!("got: {}", rx.recv().unwrap());
    sender.join().unwrap();

    let (_tx, rx) = mpsc::channel::<i32>();
    println!("{:?}", rx.recv_timeout(Duration::from_millis(50)));
}
Output
total: 180
after hang-up: Err(RecvError)
got: ping
Err(Timeout)
  • Verdict: stdlib. std::sync::mpsc gives channel (unbounded), sync_channel (bounded) and cloneable senders with one receiver.
  • There is no close. The channel hangs up when all Sender values are dropped, and send and recv then return Err.
  • The module has no select. recv_timeout and try_recv give a receive with a time limit and a receive that does not block.
KotlinGitHub
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.SynchronousQueue
import kotlin.concurrent.thread

sealed interface Msg
data class Job(val value: Int) : Msg
data object Done : Msg // the end-of-stream marker

fun main() {
    val jobs = ArrayBlockingQueue<Msg>(2)
    val producers = (1..2).map { id ->
        thread {
            for (i in 1..3) jobs.put(Job(id * 10 * i))
            jobs.put(Done)
        }
    }
    var total = 0
    var finished = 0
    while (finished < producers.size) {
        when (val m = jobs.take()) {
            is Job -> total += m.value
            Done -> finished++
        }
    }
    producers.forEach { it.join() }
    println("total: $total")

    val handoff = SynchronousQueue<String>()
    val taker = thread { println("took: ${handoff.take()}") }
    handoff.put("ping") // waits for the taker: a rendezvous
    taker.join()
}
Output
total: 180
took: ping
  • Verdict: library. The Kotlin standard library has no channel. The library kotlinx.coroutines gives Channel, with suspending send and receive, close, and iteration with for that ends after close. Its default capacity is RENDEZVOUS.
  • With the standard library only, a Kotlin/JVM program uses the JDK queues, as here. A sealed type makes the end marker a separate case, so it cannot clash with a real value.
PowerShellGitHub
$jobs = [System.Collections.Concurrent.BlockingCollection[int]]::new(2) # bound 2
$consumer = Start-ThreadJob {
    $total = 0
    foreach ($v in ($using:jobs).GetConsumingEnumerable()) { $total += $v }
    $total
}
1..2 | ForEach-Object -ThrottleLimit 2 -Parallel {
    $q = $using:jobs
    foreach ($i in 1..3) { $q.Add($_ * 10 * $i) } # Add waits while the collection is full
}
$jobs.CompleteAdding() # both producers have finished
"total: $(Receive-Job $consumer -Wait -AutoRemoveJob)"
try { $jobs.Add(1) } catch { $_.Exception.InnerException.GetType().Name }

$item = 0
"TryTake on an empty collection: $($jobs.TryTake([ref]$item, 50))"
Output
total: 180
InvalidOperationException
TryTake on an empty collection: False
  • Verdict: stdlib. PowerShell has no channel of its own, but a script can use the .NET class BlockingCollection<T>. ForEach-Object -Parallel and Start-ThreadJob run script blocks on other threads, and $using: passes the same object to them.
  • CompleteAdding closes the collection. GetConsumingEnumerable then ends after the last item, and a later Add throws.
  • Named processes or named channels. In Hoare's 1978 paper, an input or output command names the other process, not a channel. Hoare discussed ports connected by channels as an alternative and did not adopt it.1 Later languages took the other path. The Go FAQ says that Go's primitives come from the part of the CSP family whose main contribution is the channel as a first-class object.11
  • Occam and Erlang. The Go FAQ names occam and Erlang as two well-known languages that stem from CSP.11 Erlang uses asynchronous messages to processes, as the next item shows.
  • Actors and mailboxes. In Erlang, all communication between processes uses asynchronous signals. The send operator ! delivers a message to a process, and the receiver takes it from its own message queue with receive.26 The target of a send is a process, not a channel, and a send does not wait. This mailbox style is the actor style. With channels, the receiver is unknown to the sender, and one channel can have several receivers.
  • Newsqueak and Limbo. The Go FAQ names both as CSP-inspired languages that shaped Go's concurrency.12
  • Output guards. Hoare allowed only input commands in guards. He discussed output guards as a more symmetric choice and left them out.1 Go's select allows both send and receive cases.8
  • Fairness. Hoare argued that a language should not require an implementation to be fair in its choice between ready guards.1 Go's select chooses uniformly at random among the ready cases and promises no other order.8 The Kotlin documentation states that its channels are fair: they serve coroutines in first-in, first-out order.22
  • Channels of channels. A channel is a value, so a request can carry its own reply channel. Effective Go shows a server that answers each request on the channel inside it.3
  • Channels and higher-order functions. A function that takes a channel and returns a fresh channel is a stage of a pipeline. Such stages compose like Higher-order function on lists, but each stage runs in its own process.

Pitfalls

A send on a closed channel panics

Close ends the stream for receivers, but a sender that still runs can send after the close. In Go, that send panics.5 Here one of two producers closes the channel, and the other producer sends after the close.

This code panics, on purpose.

package main

import "fmt"

func main() {
	ch := make(chan int)
	done := make(chan bool)
	go func() { // producer 1 closes, as if it were the only producer
		ch <- 1
		close(ch)
		done <- true
	}()
	fmt.Println(<-ch)
	<-done
	ch <- 2 // producer 2 (main) sends after the close
}

The program stops with panic: send on closed channel. The fix is a single owner of the close. With several producers, a sync.WaitGroup counts them, and one goroutine closes the channel after all of them have returned.

package main

import (
	"fmt"
	"sync"
)

func main() {
	ch := make(chan int)
	var wg sync.WaitGroup
	for id := 1; id <= 3; id++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			ch <- id
		}()
	}
	go func() {
		wg.Wait()
		close(ch) // the only close, after the last send
	}()
	sum := 0
	for v := range ch {
		sum += v
	}
	fmt.Println("sum:", sum)
}
Output
sum: 6

A forgotten close leaves range blocked

A for range loop over a channel ends only when the channel is closed.9 If the producer returns without close, the consumer waits forever: a Deadlock.

This code fails on purpose. The output below is the error.

package main

import "fmt"

func main() {
	ch := make(chan int)
	go func() {
		for i := 1; i <= 3; i++ {
			ch <- i
		}
	}()
	sum := 0
	for v := range ch {
		sum += v
	}
	fmt.Println(sum)
}

This program ends by itself, because the Go runtime finds that every goroutine is blocked. It prints fatal error: all goroutines are asleep - deadlock! and exits with status 2. The runtime finds the deadlock only when no goroutine at all can run. A server with other active goroutines hangs instead. The fix is close(ch) after the loop of the producer, or defer close(ch) at its start. In Rust, the same bug is a Sender that stays alive: a loop over rx.iter() blocks while any sender exists.14

A goroutine leak

A goroutine that blocks forever on a channel never ends, and its memory is never freed. A common cause is a receiver that gives up after a timeout. The worker then has no one to receive its result.

This code runs but gives a wrong answer on purpose.

package main

import (
	"fmt"
	"runtime"
	"time"
)

func fetch() <-chan string {
	ch := make(chan string) // unbuffered: the send waits for a receiver
	go func() {
		time.Sleep(100 * time.Millisecond)
		ch <- "result"
	}()
	return ch
}

func main() {
	select {
	case r := <-fetch():
		fmt.Println(r)
	case <-time.After(10 * time.Millisecond):
		fmt.Println("timeout")
	}
	time.Sleep(200 * time.Millisecond) // the worker has tried to send by now
	fmt.Println("goroutines:", runtime.NumGoroutine())
}
Output
timeout
goroutines: 2

The worker still waits at ch <- "result". The fix is a buffer of one, so the send always completes and the worker returns. Another fix is a cancel channel that the worker selects on.

package main

import (
	"fmt"
	"runtime"
	"time"
)

func fetch() <-chan string {
	ch := make(chan string, 1) // room for the result, even if nobody receives it
	go func() {
		time.Sleep(100 * time.Millisecond)
		ch <- "result"
	}()
	return ch
}

func main() {
	select {
	case r := <-fetch():
		fmt.Println(r)
	case <-time.After(10 * time.Millisecond):
		fmt.Println("timeout")
	}
	time.Sleep(200 * time.Millisecond)
	fmt.Println("goroutines:", runtime.NumGoroutine())
}
Output
timeout
goroutines: 1

An unbuffered send with no receiver

On an unbuffered channel, a send waits until a receiver is ready.4 A send in the same goroutine that would later receive can never complete.

This code fails on purpose. The output below is the error.

package main

import "fmt"

func main() {
	ch := make(chan int)
	ch <- 1 // waits for a receiver that never comes
	fmt.Println(<-ch)
}

The runtime reports all goroutines are asleep - deadlock!, as before. Two fixes exist. Start the receiver in another goroutine before the send, or give the channel a buffer that holds the value. Other runtimes have no such check. A Python put on a full queue or a Java put on a SynchronousQueue with no taker waits forever. A time limit turns the hang into an error that the program can handle.

import queue

q = queue.Queue(maxsize=1)
q.put("first")
try:
    q.put("second", timeout=0.05)  # no consumer takes "first"
except queue.Full:
    print("queue full: no consumer")
Output
queue full: no consumer

Cost

  • A handover per value. Each send and receive synchronizes the two sides and can wake a waiting process. A value that moves through an unbuffered channel makes the two processes meet each time. For a reference count, Effective Go says that a mutex around an integer variable may be the better choice.2
  • Buffers trade memory for fewer waits. A buffer lets the producer run ahead of the consumer, so fewer sends block. A bounded buffer of n values needs memory for n values. An unbounded channel can use memory without limit when the consumer is slower than the producer.13
  • Copies. In Hoare's model, the output command copies the value to the receiver.1 A channel of pointers copies only the pointer, and the two processes then share the object, so the sender must stop using it. Node.js copies the whole value with the structured clone algorithm, unless the value is in the transfer list, which moves an ArrayBuffer or a port to the receiver.21
  • Threads or coroutines. A Java take or a Python get blocks the calling thread while it waits (see Thread). A Kotlin channel suspends the coroutine at send and receive instead of blocking,22 and a .NET channel makes the producer wait asynchronously.18

History

  • 1978. C. A. R. Hoare published "Communicating Sequential Processes" in Communications of the ACM. Input and output commands synchronize the two processes, and input guards select among ready communications.1
  • Java 1.5. Java 1.5 added BlockingQueue and SynchronousQueue to java.util.concurrent.1617
  • .NET Core 3.0. .NET Core 3.0 made System.Threading.Channels part of the shared framework; before that it was a NuGet package.18
  • Python 3.13. Python 3.13 added Queue.shutdown and the ShutDown exception, so a queue can be closed without a sentinel.20

References

  1. C. A. R. Hoare, Communicating Sequential Processes, Communications of the ACM 21(8), 1978, pages 666 to 677, section 1 (proposals 2 to 6); 5.1 Bounded Buffer; 7.3 Port Names; 7.4 Automatic Buffering; 7.6 Fairness; 7.8 Output Guards
  2. Effective Go, Concurrency, Share by communicating
  3. Effective Go, Concurrency, Channels; Channels of channels
  4. The Go Programming Language Specification, Channel types
  5. The Go Programming Language Specification, Send statements
  6. The Go Programming Language Specification, Receive operator
  7. The Go Programming Language Specification, Built-in functions, Close
  8. The Go Programming Language Specification, Select statements
  9. The Go Programming Language Specification, For statements with range clause
  10. The Go Memory Model, Synchronization, Channel communication
  11. Go FAQ, Why build concurrency on the ideas of CSP?
  12. Go FAQ, What are Go's ancestors?
  13. The Rust Standard Library, Module std::sync::mpsc, module description; Disconnection; Functions channel and sync_channel
  14. The Rust Standard Library, Struct std::sync::mpsc::Receiver, methods recv, recv_timeout, try_recv and iter
  15. The Rust Standard Library, Module std::sync::mpmc, module header (nightly-only experimental API, mpmc_channel)
  16. Java SE 25 API, Class SynchronousQueue, class description
  17. Java SE 25 API, Interface BlockingQueue, interface description (method table, close and shutdown, memory consistency effects)
  18. .NET documentation, System.Threading.Channels library, introduction; Bounding strategies; Bounded channels (Full mode behavior); Producer APIs; Consumer APIs
  19. .NET API reference, BlockingCollection<T> Class, class description; methods CompleteAdding, GetConsumingEnumerable and TakeFromAny
  20. The Python Standard Library, queue, Python 3.14, module description; queue.Queue; Queue.task_done; Queue.join; Queue.shutdown
  21. Node.js documentation, Worker threads, Class MessageChannel; port.postMessage(value[, transferList]); port.close(); worker_threads.receiveMessageOnPort(port)
  22. Kotlin documentation, Channels, Channel basics; Closing and iteration over channels; Buffered channels
  23. kotlinx.coroutines API, Channel() factory function, signature (capacity = RENDEZVOUS)
  24. Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.condition.condvar], paragraph 8
  25. POSIX.1-2024, pthread_cond_wait, APPLICATION USAGE and DESCRIPTION (spurious wakeups)
  26. Erlang System Documentation, Processes, Signals
  27. POSIX.1-2024, Shell Command Language, 2.9.2 Pipelines
  28. POSIX.1-2024, mkfifo utility, 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.

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