Modula-2 coroutines
last modified November 27, 2026 Modula-2
A coroutine is a procedure that can stop in the middle of its work, hand control to another coroutine, and later continue from the same place. Each coroutine has its own stack, so its local variables and its position survive the pause. Only one coroutine runs at a time, and control passes only where the program says so; nothing is interrupted from outside.
Modula-2 had coroutines from the start. Wirth's PIM put them into the
SYSTEM module as NEWPROCESS and
TRANSFER; ISO 10514 moved them into a module of their own,
COROUTINES. The article uses the ISO module, compiled with
-fiso, and shows the PIM version at the end. GNU Modula-2
builds each coroutine on a thread of the operating system, but it lets
only one of them run at a time, so the program behaves as if it had a
single thread.
Two coroutines
The main program is a coroutine too. The example creates a second one and passes control back and forth three times.
MODULE ping;
FROM COROUTINES IMPORT COROUTINE, NEWCOROUTINE, TRANSFER;
FROM SYSTEM IMPORT ADDRESS;
FROM Storage IMPORT ALLOCATE;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
CONST
Space = 64 * 1024;
VAR
boss, worker: COROUTINE;
workspace: ADDRESS;
i: CARDINAL;
PROCEDURE Work;
BEGIN
LOOP
WriteString(" worker"); WriteLn;
TRANSFER(worker, boss)
END
END Work;
BEGIN
ALLOCATE(workspace, Space);
NEWCOROUTINE(Work, workspace, Space, worker);
FOR i := 1 TO 3 DO
WriteString("main "); WriteCard(i, 0); WriteLn;
TRANSFER(boss, worker)
END;
WriteString("main done"); WriteLn
END ping.
NEWCOROUTINE(Work, workspace, Space, worker) creates a
coroutine whose body is the parameterless procedure Work.
The second and third parameters give it a workspace of 64 KB from the
heap. The workspace is an ADDRESS, the untyped pointer of
the SYSTEM module, and ALLOCATE from
Storage fills it with the address of a new block, as it does
for NEW. The last parameter returns the identity, a value of the opaque type
COROUTINE. The new coroutine does not run yet.
TRANSFER(boss, worker) stores the identity of the running
coroutine, the main program, in boss and continues
worker. The first transfer starts Work at its
beginning; every later one resumes it after its own
TRANSFER(worker, boss), which hands control back to the main
program. The main program does not have to be created; its identity
appears in boss with the first transfer. The variable could
not be called main: gm2 reserves that name for the C entry
point of the program, and a module-level main is rejected
with "symbol ‘main’ is already declared in this scope". When the main
program ends, the program ends, and the worker, which is waiting in its
loop, goes with it.
$ gm2 -fiso ping.mod -o ping $ ./ping main 1 worker main 2 worker main 3 worker main done
When a coroutine ends
A coroutine body must never reach its end. There is no caller to return to: a coroutine was not called, it was transferred to. The next program lets the worker stop after two rounds, while the main program wants three.
MODULE ending;
FROM COROUTINES IMPORT COROUTINE, NEWCOROUTINE, TRANSFER;
FROM SYSTEM IMPORT ADDRESS;
FROM Storage IMPORT ALLOCATE;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
CONST
Space = 64 * 1024;
VAR
boss, worker: COROUTINE;
workspace: ADDRESS;
i: CARDINAL;
PROCEDURE Work;
VAR
k: CARDINAL;
BEGIN
FOR k := 1 TO 2 DO
WriteString(" worker "); WriteCard(k, 0); WriteLn;
TRANSFER(worker, boss)
END
END Work;
BEGIN
ALLOCATE(workspace, Space);
NEWCOROUTINE(Work, workspace, Space, worker);
FOR i := 1 TO 3 DO
WriteString("main "); WriteCard(i, 0); WriteLn;
TRANSFER(boss, worker)
END;
WriteString("main done"); WriteLn
END ending.
The worker now counts its rounds in a local variable k,
which keeps its value between transfers. After the second round the main
program transfers to it once more, the FOR loop ends, and
Work reaches its END. GNU Modula-2 stops the
program with "execThread should never finish" and exit status 1, and the
last line of the main program is never printed. The message is glued to
main 3, because an ISO channel writes a line mark only with
the next output, as the environment
and processes article shows. A coroutine that has
finished its work must transfer to another coroutine instead, as the
producer in the last example does, or wait in a loop like the first
worker.
$ gm2 -fiso ending.mod -o ending $ ./ending main 1 worker 1 main 2 worker 2 main 3../../../../src/libgm2/libm2iso/RTco.cc:323:in execThread has caused execThread should never finish $ echo $? 1
The workspace
In ISO Modula-2 the workspace holds the stack of the coroutine, and its size says how deep the coroutine may call procedures. GNU Modula-2 uses the size for the stack of the underlying thread and ignores the address. The program creates three coroutines with workspaces of decreasing size.
MODULE workspace;
FROM COROUTINES IMPORT COROUTINE, NEWCOROUTINE;
FROM SYSTEM IMPORT ADDRESS;
FROM Storage IMPORT ALLOCATE;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
VAR
c: COROUTINE;
PROCEDURE Idle;
BEGIN
LOOP END
END Idle;
PROCEDURE Make(size: CARDINAL);
VAR
space: ADDRESS;
BEGIN
WriteString("workspace of "); WriteCard(size, 0); WriteLn;
ALLOCATE(space, size);
NEWCOROUTINE(Idle, space, size, c);
WriteString(" created"); WriteLn
END Make;
BEGIN
Make(1024 * 1024);
Make(16 * 1024);
Make(4 * 1024)
END workspace.
The message is glued to the last line for the same reason as before.
The coroutines are only created, never started, so Idle
never runs. One megabyte and 16 KB are accepted; 4 KB is below the
smallest stack that the thread library allows, and the program aborts
with "failed to set stack size attribute". On Linux the limit is 16 KB. A
size of 0 is also accepted and gives the default thread stack of 8 MB.
The 64 KB used in the other examples are plenty for coroutines that call
only a few procedures; a coroutine that recurses deeply needs more, and
overrunning the stack is a segmentation fault without a message.
$ gm2 -fiso workspace.mod -o workspace $ ./workspace workspace of 1048576 created workspace of 16384 created workspace of 4096../../../../src/libgm2/libm2iso/RTco.cc:379:in initThread has caused failed to set stack size attribute $ echo $? 1
A generator
A coroutine can produce a sequence one value at a time. The caller asks for the next value, the coroutine computes it, hands it over and waits for the next request with all its local variables intact.
MODULE fibgen;
FROM COROUTINES IMPORT COROUTINE, NEWCOROUTINE, TRANSFER;
FROM SYSTEM IMPORT ADDRESS;
FROM Storage IMPORT ALLOCATE;
FROM STextIO IMPORT WriteLn;
FROM SWholeIO IMPORT WriteCard;
CONST
Space = 64 * 1024;
VAR
boss, gen: COROUTINE;
workspace: ADDRESS;
value: CARDINAL;
i: CARDINAL;
PROCEDURE Fibonacci;
VAR
a, b, t: CARDINAL;
BEGIN
a := 0; b := 1;
LOOP
value := a;
TRANSFER(gen, boss);
t := a + b; a := b; b := t
END
END Fibonacci;
PROCEDURE Next(): CARDINAL;
BEGIN
TRANSFER(boss, gen);
RETURN value
END Next;
BEGIN
ALLOCATE(workspace, Space);
NEWCOROUTINE(Fibonacci, workspace, Space, gen);
FOR i := 1 TO 12 DO
WriteCard(Next(), 4)
END;
WriteLn;
WHILE Next() < 1000 DO END;
WriteCard(value, 0); WriteLn
END fibgen.
Fibonacci keeps the last two numbers in its locals
a and b. It stores the current number in the
module variable value, transfers back, and computes the next
number only when it is resumed. Next hides the transfer, so
the main program reads the sequence like a function. The first loop takes
twelve numbers, and the WHILE loop with an empty body keeps
asking until a number reaches 1000. The generator never ends; it simply
is not resumed any more. Written as an ordinary procedure, the same
generator would have to keep a and b in global
variables between calls.
$ gm2 -fiso fibgen.mod -o fibgen $ ./fibgen 0 1 1 2 3 5 8 13 21 34 55 89 1597
Producer and consumer
In the classic use of coroutines, one coroutine produces data and another consumes it, and neither calls the other. The producer cuts a sentence into words, the consumer numbers and measures them, and the main program only starts the pair.
MODULE words;
FROM COROUTINES IMPORT COROUTINE, NEWCOROUTINE, TRANSFER;
FROM SYSTEM IMPORT ADDRESS;
FROM Storage IMPORT ALLOCATE;
FROM Strings IMPORT Length;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
CONST
Space = 64 * 1024;
Text = "Modula-2 has coroutines in its SYSTEM module";
VAR
boss, producer, consumer: COROUTINE;
word: ARRAY [0..31] OF CHAR;
PROCEDURE Produce;
VAR
text: ARRAY [0..63] OF CHAR;
i, n: CARDINAL;
BEGIN
text := Text;
i := 0;
WHILE i < Length(text) DO
n := 0;
WHILE (i < Length(text)) AND (text[i] # ' ') DO
word[n] := text[i]; INC(n); INC(i)
END;
word[n] := 0C;
INC(i);
TRANSFER(producer, consumer)
END;
TRANSFER(producer, boss)
END Produce;
PROCEDURE Consume;
VAR
count: CARDINAL;
BEGIN
count := 0;
LOOP
INC(count);
WriteCard(count, 2); WriteString(" "); WriteString(word);
WriteString(" ("); WriteCard(Length(word), 0); WriteString(")");
WriteLn;
TRANSFER(consumer, producer)
END
END Consume;
PROCEDURE Spawn(body: PROC; VAR c: COROUTINE);
VAR
workspace: ADDRESS;
BEGIN
ALLOCATE(workspace, Space);
NEWCOROUTINE(body, workspace, Space, c)
END Spawn;
BEGIN
Spawn(Produce, producer);
Spawn(Consume, consumer);
TRANSFER(boss, producer);
WriteString("all words consumed"); WriteLn
END words.
Spawn allocates a workspace and creates a coroutine, so the
main program creates two of them in two lines. The main program transfers
to the producer and waits. The producer copies one word into the shared
word and transfers to the consumer, which prints it and
transfers back. Each of them continues exactly where it stopped: the
producer in the middle of its WHILE loop with its index
i, the consumer in its LOOP with its counter.
After the last word the producer transfers to the main program and is
never resumed, so it does not reach its end. The two coroutines are
symmetric partners; either side could be rewritten without turning the
other into a procedure called once per word.
$ gm2 -fiso words.mod -o words $ ./words 1 Modula-2 (8) 2 has (3) 3 coroutines (10) 4 in (2) 5 its (3) 6 SYSTEM (6) 7 module (6) all words consumed
The PIM version
In PIM the same facilities live in SYSTEM: the type
PROCESS and the procedures NEWPROCESS and
TRANSFER. Despite the name, a PROCESS is a
coroutine. The first example looks like this in PIM, with the output of
InOut.
MODULE pimping;
FROM SYSTEM IMPORT PROCESS, NEWPROCESS, TRANSFER, ADDRESS;
FROM Storage IMPORT ALLOCATE;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
CONST
Space = 64 * 1024;
VAR
boss, worker: PROCESS;
workspace: ADDRESS;
i: CARDINAL;
PROCEDURE Work;
BEGIN
LOOP
WriteString(" worker"); WriteLn;
TRANSFER(worker, boss)
END
END Work;
BEGIN
ALLOCATE(workspace, Space);
NEWPROCESS(Work, workspace, Space, worker);
FOR i := 1 TO 3 DO
WriteString("main "); WriteCard(i, 0); WriteLn;
TRANSFER(boss, worker)
END;
WriteString("main done"); WriteLn
END pimping.
Apart from the names the program is the same, and so is its output. The
PIM SYSTEM exists only in the PIM dialects, the default of
gm2. With -fiso the compiler takes the ISO
SYSTEM, which has no coroutines, and reports the three names
as unknown.
$ gm2 pimping.mod -o pimping $ ./pimping main 1 worker main 2 worker main 3 worker main done $ gm2 -fiso pimping.mod -o pimping 2>&1 | grep unresolved /usr/lib/gcc/x86_64-linux-gnu/15/m2/m2iso/SYSTEM.def:267:11: error: the following unknown symbols in module ‘SYSTEM’ were unresolved: TRANSFER, NEWPROCESS and PROCESS
Source
GNU Modula-2: the COROUTINES module
GNU Modula-2: the PIM SYSTEM module
In this article we have created coroutines with NEWCOROUTINE,
passed control between them with TRANSFER, seen what happens
when a coroutine reaches its end or gets too small a workspace, and
written a generator, a producer and a consumer, and the PIM version with
NEWPROCESS. Coroutines decide themselves when to pass
control; the processes and
semaphores article adds a scheduler that makes that decision. The
procedure types article covers the
PROC type of a coroutine body.
Author
List all Modula-2 tutorials.