Programming Search⌘K

Conceptcore

Message passing

Also called message passing, message-passing concurrency, send and receive, mailbox, inbox, producer-consumer queue, share memory by communicating, inter-process communication, IPC, postMessage.

In message passing, parts of a program work together by sending each other messages instead of changing shared variables. Each part owns its own state and changes it only when a message arrives.

Applies to
core-languages

Idea

When two threads change the same variable, they need a lock, and a missing lock is a bug that shows up only sometimes. Message passing removes the shared variable. One part of the program owns the data. Other parts send it messages, such as "add 1" or "tell me the total", and the owner handles one message at a time. Because only the owner touches the data, no lock protects it.

import queue
import threading


# The total lives in one thread. Other code changes it only by sending messages.
def counter(inbox):
    total = 0
    while True:
        message = inbox.get()
        if message[0] == "add":
            total += message[1]
        elif message[0] == "get":
            message[1].put(total)
        elif message[0] == "stop":
            return


inbox = queue.Queue()
worker = threading.Thread(target=counter, args=(inbox,))
worker.start()


# Four threads send 1000 messages each. They share no variable, so they need no lock.
def sender():
    for _ in range(1000):
        inbox.put(("add", 1))


senders = [threading.Thread(target=sender) for _ in range(4)]
for t in senders:
    t.start()
for t in senders:
    t.join()

# To read the total, send a request that carries a queue for the reply.
reply = queue.Queue()
inbox.put(("get", reply))
print("total:", reply.get())

inbox.put(("stop",))
worker.join()
print("worker stopped:", not worker.is_alive())
Output
total: 4000
worker stopped: True

The counter thread owns total. Four other threads send 4000 messages in total, and the queue delivers them one at a time, so the result is always 4000 with no lock in the program. To read the total, the main thread sends a get message with a queue for the reply and waits on that queue. The stop message tells the worker to end.

How it works

Send, receive and the owner. Wikipedia defines message passing as "a technique for invoking behavior (i.e., running a program) on a computer"1. "The invoking program sends a message to a process (which may be an actor or object) and relies on that process and its supporting infrastructure to then select and run some appropriate code"1. The receiver decides what a message means, so the sender does not need access to the state of the receiver. The Go documentation puts the rule in one line: "Do not communicate by sharing memory; instead, share memory by communicating"2. Values go from one goroutine to another on channels, so "Only one goroutine has access to the value at any given time. Data races cannot occur, by design"2.

Channels and mailboxes. A message needs a path from the sender to the receiver. There are two common forms:

  • A channel is a typed pipe that any holder of one end can use. "A channel is a general programming concept by which data is sent from one thread to another"3. Go, Rust, C# and Kotlin have channels. See channels.
  • A mailbox belongs to one process or actor. In Erlang, "Each process has its own input queue for messages it receives. New messages received are put at the end of the queue"4, and receive takes the first message that matches a pattern. See the actor model.

Synchronous and asynchronous. In synchronous message passing, "the sending process waits until the receiving process accepts the message"1. A Go channel with no buffer works this way: "communication succeeds only when both a sender and receiver are ready"5. In asynchronous message passing, the message waits in a queue and the sender continues. A queue with a limit makes a choice when it is full. Wikipedia says that "A decision has to be made whether to block the sender or whether to discard future messages. A blocked sender may lead to deadlock"1.

Copy or move. A message must not leave shared state behind. Processes have separate memory, so a message between processes is a copy. Python multiprocessing "supports two types of communication channel between processes"6, queues and pipes. "When an object is put on a queue, the object is pickled"6, so the receiver gets a copy. A JavaScript worker gets a copy too: "The data may be any JavaScript object that can be handled by the structured clone algorithm"7. Threads share memory, so the language must stop the sender from using the value after the send. Rust does this with ownership: "The send function takes ownership of its parameter, and when the value is moved the receiver takes ownership of it"3. In Java, Go and C#, the sender can keep a reference to a mutable object that it sent, so the rule is a convention. Send immutable values, or do not touch an object after you send it.

Request and reply. A message goes in one direction. To get an answer, the request carries a place for the reply, such as a reply channel or the identifier of the sender. The idea example, the Go example and the Rust example all send a reply channel inside the request.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaStandard library
CIdiom
C#Standard library
JavaScriptNative
TypeScriptNativeTypeScript uses the postMessage API of workers and MessageChannel ports, as JavaScript does, and can give the message data a type. The message is a structured clone. No example file exists.
GoNative
RustStandard library
KotlinLibraryThe kotlinx.coroutines library has Channel, with send and receive functions that suspend the coroutine, and close to end the stream. It is not part of the Kotlin standard library. No example file exists because kotlinc is not installed.
SQLDoes not applyA query has no concurrent parts that send messages. Some databases add queues or notifications, such as LISTEN and NOTIFY in PostgreSQL, but standard SQL does not have them. No example file exists.
BashIdiomA pipeline sends the output of one process to the input of the next, and a named pipe made with mkfifo connects processes that do not start together. The messages are bytes. No example file exists.
PowerShellIdiomThe PowerShell pipeline passes objects from one command to the next, and background jobs send their output back to the caller. There are no channels between threads in the language. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and does not run code. Messages between windows and workers use the postMessage API of JavaScript.
CSSDoes not applyCSS has no concurrent parts and no messages.
Regular expressionsDoes not applyA regular expression has no concurrent parts and no messages.
Language Verdict Mechanism
Python stdlib queue.Queue between threads; multiprocessing.Queue and Pipe between processes; asyncio.Queue
JavaScript native postMessage to workers and MessageChannel ports; messages are structured clones
TypeScript native the same postMessage API, with types for the message data
Java stdlib BlockingQueue implementations in java.util.concurrent
Kotlin library Channel in kotlinx.coroutines, with send and receive
C# stdlib System.Threading.Channels, with bounded and unbounded channels
Go native chan types, the <- operator, select and close
Rust stdlib std::sync::mpsc channels in the standard library; ownership moves the message
C idiom no language support; POSIX pipes, sockets and message queues, or MPI
C++ idiom no standard channel; a queue with a mutex and a condition variable, or a library
Bash idiom a pipeline sends the output of one process to the input of the next; named pipes
PowerShell idiom the pipeline passes objects from one command to the next; jobs return output
SQL n/a no messages between parts of a query; some databases add queues and LISTEN and NOTIFY
Regex n/a a pattern does not run concurrent parts
HTML n/a HTML is markup; postMessage is part of the JavaScript API
CSS n/a CSS has no concurrent parts

Go is the only language of the set with channels in the syntax. In JavaScript and TypeScript, a worker cannot share ordinary objects, so the message is always a copy. In the other languages, message passing is a library on top of threads that share memory, and the program must not share the data that it sends.

The example files show these differences. Python moves work to another process through a multiprocessing.Queue, shows that a list sent through a Pipe is a copy, and writes an account in the message-passing style of SICP. JavaScript sends an array to a worker and shows that the worker changed a copy, that a function cannot be cloned and that a MessageChannel connects two ports. Java uses a LinkedBlockingQueue as an inbox, and shows that a full ArrayBlockingQueue and a SynchronousQueue with no waiting receiver refuse offer. C# uses unbounded and bounded channels with the full modes Wait and DropOldest. Go uses select, a buffered channel, close and a pool of workers. Rust has many producers that each clone the sender, and shows that send moves the value. C passes numbers to a child process through a pipe. C++ builds a channel from a mutex, a condition variable and a queue.

PythonGitHub
from multiprocessing import Pipe, Process, Queue


def square_all(inbox, outbox):
    while (n := inbox.get()) is not None:
        outbox.put(n * n)
    outbox.put(None)


def change(conn):
    data = conn.recv()
    data.append("changed in child")
    conn.send(data)
    conn.close()


def make_account(balance):
    # Message passing in the sense of SICP: the object is a procedure
    # that takes the name of an operation as a message.
    def dispatch(message, amount=0):
        nonlocal balance
        if message == "deposit":
            balance += amount
        elif message == "withdraw":
            balance -= amount
        elif message == "balance":
            return balance
        else:
            raise ValueError("unknown message: " + message)

    return dispatch


if __name__ == "__main__":
    # A process takes messages from one queue and sends results on another.
    inbox, outbox = Queue(), Queue()
    p = Process(target=square_all, args=(inbox, outbox))
    p.start()
    for n in [1, 2, 3, 4]:
        inbox.put(n)
    inbox.put(None)
    results = []
    while (r := outbox.get()) is not None:
        results.append(r)
    p.join()
    print(results)

    # A message is a copy: the child changes its copy, not the list of the parent.
    parent_end, child_end = Pipe()
    data = ["original"]
    p = Process(target=change, args=(child_end,))
    p.start()
    parent_end.send(data)
    print(parent_end.recv(), data)
    p.join()

    account = make_account(100)
    account("deposit", 50)
    account("withdraw", 30)
    print(account("balance"))
    try:
        account("close")
    except ValueError as e:
        print(e)
Output
[1, 4, 9, 16]
['original', 'changed in child'] ['original']
120
unknown message: close
  • Verdict: stdlib. A multiprocessing.Queue carries numbers to another process, and a second queue carries the squares back, with None as the end of the stream. A list sent through a Pipe is pickled, so the child changes a copy and the list of the parent stays ['original']. The account is message passing in the sense of SICP: a procedure that takes the name of an operation.
#include <condition_variable>
#include <deque>
#include <mutex>
#include <optional>
#include <print>
#include <string>
#include <thread>
#include <vector>

// The standard library has no channel, so this one is built from a mutex,
// a condition variable and a queue.
template <typename T>
class Channel {
public:
    void send(T value) {
        {
            std::lock_guard lock(m_);
            q_.push_back(std::move(value));
        }
        cv_.notify_one();
    }

    void close() {
        {
            std::lock_guard lock(m_);
            closed_ = true;
        }
        cv_.notify_all();
    }

    // Waits for a message, and gives nullopt when the channel is closed and empty.
    std::optional<T> receive() {
        std::unique_lock lock(m_);
        cv_.wait(lock, [this] { return !q_.empty() || closed_; });
        if (q_.empty()) {
            return std::nullopt;
        }
        T v = std::move(q_.front());
        q_.pop_front();
        return v;
    }

private:
    std::mutex m_;
    std::condition_variable cv_;
    std::deque<T> q_;
    bool closed_ = false;
};

int main() {
    Channel<int> numbers;
    long total = 0;
    // The consumer thread is the only code that touches total.
    std::thread consumer([&] {
        while (auto n = numbers.receive()) {
            total += *n;
        }
    });
    {
        std::vector<std::jthread> producers;
        for (int i = 0; i < 4; i++) {
            producers.emplace_back([&] {
                for (int k = 0; k < 1000; k++) {
                    numbers.send(1);
                }
            });
        }
    }  // The jthreads join here.
    numbers.close();
    consumer.join();
    std::println("total {}", total);

    // A string moved into the channel is transferred, not copied.
    Channel<std::string> texts;
    std::string s = "hello";
    texts.send(std::move(s));
    texts.close();
    std::println("{} {}", texts.receive().value_or("none"), texts.receive().has_value());
}
Output
total 4000
hello false
  • Verdict: idiom. The standard library has no channel, so the example builds one from a std::mutex, a std::condition_variable and a std::deque. receive waits for a message and gives std::nullopt after close. Four std::jthread producers send 4000 messages to one consumer. A std::string moved into the channel is transferred, not copied.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;

public class Main {
    record Message(String kind, int value) {}

    public static void main(String[] args) throws InterruptedException {
        // A worker thread owns the total and changes it only when a message arrives.
        BlockingQueue<Message> inbox = new LinkedBlockingQueue<>();
        BlockingQueue<Integer> replies = new LinkedBlockingQueue<>();
        Thread worker = new Thread(() -> {
            int total = 0;
            try {
                while (true) {
                    Message m = inbox.take();
                    switch (m.kind()) {
                        case "add" -> total += m.value();
                        case "get" -> replies.put(total);
                        case "stop" -> {
                            return;
                        }
                        default -> throw new IllegalStateException(m.kind());
                    }
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        worker.start();

        // Four senders put messages on the queue. They share no counter, so they need no lock.
        List<Thread> senders = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Thread t = new Thread(() -> {
                for (int k = 0; k < 1000; k++) {
                    inbox.add(new Message("add", 1));
                }
            });
            senders.add(t);
            t.start();
        }
        for (Thread t : senders) {
            t.join();
        }
        inbox.put(new Message("get", 0));
        System.out.println("total " + replies.take());
        inbox.put(new Message("stop", 0));
        worker.join();

        // A bounded queue refuses a message when it is full.
        BlockingQueue<String> small = new ArrayBlockingQueue<>(2);
        System.out.println(small.offer("a") + " " + small.offer("b") + " " + small.offer("c") + " " + small.remainingCapacity());

        // A SynchronousQueue has no buffer: offer fails unless a receiver waits.
        BlockingQueue<String> handoff = new SynchronousQueue<>();
        System.out.println(handoff.offer("x"));
    }
}
Output
total 4000
true true false 0
false
  • Verdict: stdlib. A worker thread takes messages from a LinkedBlockingQueue and owns the total, so 4000 messages from four threads give 4000 with no lock. A get message gets its answer on a second queue. A full ArrayBlockingQueue refuses offer, and a SynchronousQueue refuses offer when no receiver waits.
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>

/* C has no message passing in the language. POSIX gives processes pipes,
   which carry bytes from one process to another. */
int main(void) {
    int to_child[2];
    int to_parent[2];
    if (pipe(to_child) != 0 || pipe(to_parent) != 0) {
        return 1;
    }
    int counter = 10;
    pid_t pid = fork();
    if (pid < 0) {
        return 1;
    }
    if (pid == 0) {
        /* The child has its own copy of the memory, so this does not change the parent. */
        counter = 99;
        close(to_child[1]);
        close(to_parent[0]);
        int n;
        int sum = 0;
        while (read(to_child[0], &n, sizeof n) == (ssize_t)sizeof n) {
            sum += n;
        }
        write(to_parent[1], &sum, sizeof sum);
        write(to_parent[1], &counter, sizeof counter);
        _exit(0);
    }
    close(to_child[0]);
    close(to_parent[1]);
    for (int n = 1; n <= 5; n++) {
        write(to_child[1], &n, sizeof n);
    }
    /* Closing the write end tells the child that no more messages come. */
    close(to_child[1]);
    int sum = 0;
    int child_counter = 0;
    read(to_parent[0], &sum, sizeof sum);
    read(to_parent[0], &child_counter, sizeof child_counter);
    waitpid(pid, NULL, 0);
    printf("sum %d\n", sum);
    printf("child counter %d, parent counter %d\n", child_counter, counter);
    return 0;
}
Output
sum 15
child counter 99, parent counter 10
  • Verdict: idiom. The language has no message passing, so the example uses POSIX pipe and fork. The parent writes five integers, closes the pipe to mark the end, and reads the sum from a second pipe. The child sets counter to 99 in its own copy of the memory, so the parent still has 10.
using System.Threading.Channels;

// A consumer task owns the total; producers send it numbers through a channel.
var channel = Channel.CreateUnbounded<int>();
var consumer = Task.Run(async () =>
{
    int total = 0;
    await foreach (int n in channel.Reader.ReadAllAsync())
    {
        total += n;
    }
    return total;
});
var producers = Enumerable.Range(0, 4).Select(_ => Task.Run(async () =>
{
    for (int k = 0; k < 1000; k++)
    {
        await channel.Writer.WriteAsync(1);
    }
})).ToArray();
await Task.WhenAll(producers);
channel.Writer.Complete();
Console.WriteLine($"total {await consumer}");

// A bounded channel in Wait mode refuses TryWrite when it is full.
var small = Channel.CreateBounded<string>(new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.Wait });
Console.WriteLine($"{small.Writer.TryWrite("a")} {small.Writer.TryWrite("b")} {small.Writer.TryWrite("c")} {small.Reader.Count}");

// DropOldest makes room by discarding the oldest message.
var latest = Channel.CreateBounded<int>(new BoundedChannelOptions(2) { FullMode = BoundedChannelFullMode.DropOldest });
foreach (int i in new[] { 1, 2, 3, 4 })
{
    latest.Writer.TryWrite(i);
}
latest.Writer.Complete();
var kept = new List<int>();
await foreach (int i in latest.Reader.ReadAllAsync())
{
    kept.Add(i);
}
Console.WriteLine(string.Join(" ", kept));

// After Complete, a write fails.
Console.WriteLine(latest.Writer.TryWrite(5));
Output
total 4000
True True False 2
3 4
False
  • Verdict: stdlib. Four producer tasks write to an unbounded Channel<int>, and one consumer reads with ReadAllAsync until Complete. A bounded channel in Wait mode refuses the third TryWrite. In DropOldest mode it keeps the last two of four messages. A write after Complete fails.
JavaScriptGitHub
const { Worker, MessageChannel } = require("node:worker_threads");

// The worker runs in its own thread with its own memory. It answers each message.
const code = `
const { parentPort } = require("node:worker_threads");
parentPort.on("message", (msg) => {
  msg.items.push("added by worker");
  const sum = msg.items.filter((x) => typeof x === "number").reduce((a, b) => a + b, 0);
  parentPort.postMessage({ sum, items: msg.items });
});
`;

function ask(worker, msg) {
  return new Promise((resolve) => {
    worker.once("message", resolve);
    worker.postMessage(msg);
  });
}

async function main() {
  const worker = new Worker(code, { eval: true });
  const items = [1, 2, 3];
  const reply = await ask(worker, { items });
  // The message is a structured clone, so the worker changed a copy.
  console.log(reply.sum, reply.items.join(","), "|", items.join(","));
  await worker.terminate();

  // A Map and a Date survive the clone, but a function does not.
  const copy = structuredClone({ when: new Date(0), tags: new Map([["a", 1]]) });
  console.log(copy.when.toISOString(), copy.tags.get("a"));
  try {
    structuredClone({ f: () => 1 });
  } catch (e) {
    console.log(e.name);
  }

  // A MessageChannel has two ports: a message sent on one arrives on the other.
  const { port1, port2 } = new MessageChannel();
  const got = new Promise((resolve) => port2.once("message", resolve));
  port1.postMessage("hello");
  console.log(await got);
  port1.close();
}

main();
Output
6 1,2,3,added by worker | 1,2,3
1970-01-01T00:00:00.000Z 1
DataCloneError
hello
  • Verdict: native. postMessage sends an array to a worker, and the worker adds an item to its copy, so the array of the main thread is not changed. structuredClone keeps a Date and a Map but throws DataCloneError for a function. A message sent on one port of a MessageChannel arrives on the other port.
package main

import (
	"fmt"
	"sort"
)

type request struct {
	n     int
	reply chan int
}

func main() {
	// A goroutine owns the total; other goroutines send it messages.
	adds := make(chan int)
	gets := make(chan chan int)
	go func() {
		total := 0
		for {
			select {
			case n := <-adds:
				total += n
			case r := <-gets:
				r <- total
			}
		}
	}()
	done := make(chan bool)
	for i := 0; i < 4; i++ {
		go func() {
			for k := 0; k < 1000; k++ {
				adds <- 1
			}
			done <- true
		}()
	}
	for i := 0; i < 4; i++ {
		<-done
	}
	r := make(chan int)
	gets <- r
	fmt.Println("total", <-r)

	// A buffered channel holds messages until a receiver takes them.
	buf := make(chan string, 2)
	buf <- "a"
	buf <- "b"
	fmt.Println(len(buf), cap(buf))
	select {
	case buf <- "c":
		fmt.Println("sent c")
	default:
		fmt.Println("buffer full")
	}
	close(buf)
	var got []string
	for s := range buf {
		got = append(got, s)
	}
	fmt.Println(got)

	// A receive from a closed channel gives the zero value and false.
	v, ok := <-buf
	fmt.Printf("%q %v\n", v, ok)

	// Three workers answer requests; each request carries its reply channel.
	jobs := make(chan request)
	for w := 0; w < 3; w++ {
		go func() {
			for req := range jobs {
				req.reply <- req.n * req.n
			}
		}()
	}
	replies := make(chan int, 5)
	for n := 1; n <= 5; n++ {
		jobs <- request{n, replies}
	}
	close(jobs)
	var results []int
	for i := 0; i < 5; i++ {
		results = append(results, <-replies)
	}
	sort.Ints(results)
	fmt.Println(results)
}
Output
total 4000
2 2
buffer full
[a b]
"" false
[1 4 9 16 25]
  • Verdict: native. A goroutine owns the total and uses select to take an add or a request with a reply channel. A buffered channel with capacity 2 holds two strings, and select with default sees that it is full. range reads until close, and a receive after that gives "" and false. Three workers square numbers sent on a jobs channel.
RustGitHub
use std::sync::mpsc;
use std::thread;

enum Message {
    Add(i64),
    Get(mpsc::Sender<i64>),
    Stop,
}

fn main() {
    // A thread owns the total and changes it only when a message arrives.
    let (tx, rx) = mpsc::channel::<Message>();
    let worker = thread::spawn(move || {
        let mut total = 0;
        for msg in rx {
            match msg {
                Message::Add(n) => total += n,
                Message::Get(reply) => reply.send(total).unwrap(),
                Message::Stop => break,
            }
        }
    });

    // Each sender is a clone of tx: many producers, one consumer.
    let senders: Vec<_> = (0..4)
        .map(|_| {
            let tx = tx.clone();
            thread::spawn(move || {
                for _ in 0..1000 {
                    tx.send(Message::Add(1)).unwrap();
                }
            })
        })
        .collect();
    for s in senders {
        s.join().unwrap();
    }
    let (reply_tx, reply_rx) = mpsc::channel();
    tx.send(Message::Get(reply_tx)).unwrap();
    println!("total {}", reply_rx.recv().unwrap());
    tx.send(Message::Stop).unwrap();
    worker.join().unwrap();

    // send moves the value, so the sender cannot use it after the send.
    let (stx, srx) = mpsc::channel();
    let text = String::from("hello");
    stx.send(text).unwrap();
    // println!("{text}"); does not compile, because text was moved.
    println!("{}", srx.recv().unwrap());

    // A bounded channel refuses a message when it is full.
    let (btx, brx) = mpsc::sync_channel::<i32>(1);
    println!("{:?} {}", btx.try_send(1), btx.try_send(2).is_err());
    drop(btx);
    // When every sender is gone, the receiver gets the rest and then stops.
    println!("{:?}", brx.iter().collect::<Vec<_>>());
}
Output
total 4000
hello
Ok(()) true
[1]
  • Verdict: stdlib. mpsc::channel gives one receiver and a sender that each producer clones. A thread owns the total and matches on an enum of messages, and a Get message carries its own reply sender. send moves the String, so the sender cannot use it. try_send on a full sync_channel(1) fails, and the receiver stops after the last sender is dropped.
  • Messages to objects. In Smalltalk and in the design of Alan Kay, calling a method is sending a message to an object. Wikipedia says that "Alan Kay has argued that message passing is more important than objects in OOP"1. See objects and messages.
  • Dispatch on the operation name. SICP describes a data object that is a procedure, which takes the name of an operation and runs it. "This style of programming is called message passing"8. The Python example has an account of this form.
  • Producer and consumer queues. Java BlockingQueue is "A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element"9. In .NET, "Channels are an implementation of the producer/consumer conceptual programming model"10.
  • Message passing between machines. Sockets, HTTP, message brokers and MPI carry messages over a network. "The Message Passing Interface (MPI) is a portable message-passing standard designed to function on parallel computing architectures"11.
  • Shared memory. The other main model of concurrency uses shared variables with locks and atomic operations. See mutual exclusion. Many programs use both.

Pitfalls

  • Sharing through the message. If a thread sends a reference to a mutable object and keeps using it, the two threads share memory again, with the same data races. Send a copy, an immutable value or ownership.
  • Deadlock. Two parts that each wait for a message from the other wait forever. A full bounded queue that blocks its sender can do the same. See deadlock.
  • Queues with no limit. An unbounded queue hides a consumer that is too slow until the program runs out of memory. Use a bounded queue and decide what happens when it is full.
  • The end of the stream. A receiver must know when no more messages come. Close the channel, drop the last sender, or send a stop message. A Go receive from a closed channel gives the zero value, so check the second result.
  • Too far. Effective Go warns that "This approach can be taken too far. Reference counts may be best done by putting a mutex around an integer variable, for instance"2. A lock is simpler for one small counter.

Cost

A message between threads costs a queue operation and, when the receiver waits, a wake-up of a thread. That is much more than a write to memory, so a message should carry a useful amount of work. A message between processes also pays for the copy and for the system call, and a message over a network pays for the network. In return, the owner of the data needs no locks, and a design with messages often moves from threads to processes or to machines with few changes.

History

The actor formalism of Carl Hewitt, Peter Bishop and Richard Steiger, "A universal modular ACTOR formalism for artificial intelligence"1, appeared in 1973. "CSP was first described by Tony Hoare in a 1978 article"12. CSP is one of the process calculi "based on message passing via channels"12, and it "also influenced the design of programming languages such as Limbo"12, RaftLib, Erlang, Go, Crystal and Clojure core.async. In parallel computing, the MPI Forum wrote a standard for message passing with library routines for C, C++ and Fortran, and "version 1.0 of MPI was released in June 1994"11. The Go documentation made "share memory by communicating" a rule of style2.

References

  1. Message passing, Wikipedia, Introduction; Synchronous versus asynchronous message passing; Mathematical models; References
  2. Effective Go, Concurrency, Share by communicating
  3. Transfer Data Between Threads with Message Passing, The Rust Programming Language, Chapter 16.2
  4. Concurrent Programming, Erlang System Documentation, Message Passing
  5. The Go Programming Language Specification, Channel types; Making slices, maps and channels
  6. multiprocessing, Process-based parallelism, Python documentation, Exchanging objects between processes; Sharing state between processes
  7. Worker postMessage() method, MDN Web Docs, Introduction
  8. Structure and Interpretation of Computer Programs, 2nd edition, 2.4.3 Data-Directed Programming and Additivity, Message passing
  9. Interface BlockingQueue, Java SE 25 API, Description
  10. System.Threading.Channels library, .NET documentation, Producer/consumer conceptual programming model
  11. Message Passing Interface, Wikipedia, Introduction; History
  12. Communicating sequential processes, Wikipedia, Introduction

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