Modula-2 processes and semaphores
last modified November 27, 2026 Modula-2
The coroutines article passes control
by hand: every TRANSFER names the coroutine that runs next.
ISO Modula-2 builds two modules on top of coroutines that take this
decision away from the program. Processes keeps a list of
processes and a scheduler that picks the one to run, and
Semaphores lets processes wait for each other.
The processes are not run in parallel, and none is interrupted by a timer.
A process runs until it stops, suspends itself, waits on a semaphore or
activates a more urgent process; then the scheduler chooses the next one.
Each process has an urgency, an integer; the scheduler always
picks a ready process with the highest urgency. The main program is a
process with urgency 0. All examples are compiled with
-fiso.
Starting a process
Start creates a process and makes it ready to run. The body
is a parameterless procedure, as for a coroutine.
MODULE start;
FROM Processes IMPORT ProcessId, Start, StopMe;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
VAR
worker: ProcessId;
PROCEDURE Work;
VAR
i: CARDINAL;
BEGIN
FOR i := 1 TO 3 DO
WriteString(" worker "); WriteCard(i, 0); WriteLn
END;
StopMe
END Work;
BEGIN
WriteString("main starts the worker"); WriteLn;
Start(Work, 0, 1, NIL, worker);
WriteString("main continues"); WriteLn
END start.
Start(Work, 0, 1, NIL, worker) takes the body, the extra
workspace beyond the default, the urgency, a parameter, and returns the
identity of the new process. The worker has urgency 1, more than the main
program, so the scheduler switches to it at once, and the main program
continues only after the worker has finished. With urgency 0 the result
is the same here; with urgency -1 the worker never runs, because the main
program continues and ends the program first.
A process ends with StopMe. Like a coroutine, a process body
must not reach its END: without the StopMe, gm2
aborts with "execThread should never finish".
$ gm2 -fiso start.mod -o start $ ./start main starts the worker worker 1 worker 2 worker 3 main continues
Passive processes
Create makes a process in the passive state: it
exists but does not run until another process activates it. A process
that has done its share of work can become passive again with
SuspendMe.
MODULE passive;
FROM Processes IMPORT ProcessId, Create, Activate, SuspendMe;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
VAR
worker: ProcessId;
i: CARDINAL;
PROCEDURE Work;
VAR
runs: CARDINAL;
BEGIN
runs := 0;
LOOP
INC(runs);
WriteString(" worker run "); WriteCard(runs, 0); WriteLn;
SuspendMe
END
END Work;
BEGIN
Create(Work, 0, 1, NIL, worker);
WriteString("worker created"); WriteLn;
FOR i := 1 TO 3 DO
WriteString("main activates"); WriteLn;
Activate(worker)
END;
WriteString("main done"); WriteLn
END passive.
The worker is created passive, so worker created comes
first. Each Activate(worker) makes it ready, and since its
urgency is higher, it runs at once. It prints one line and calls
SuspendMe, which makes it passive again and lets the
scheduler return to the main program. Its local counter
runs survives between the runs, as the locals of a coroutine
do. At the end the worker is passive, and the program ends with the main
program.
$ gm2 -fiso passive.mod -o passive $ ./passive worker created main activates worker run 1 main activates worker run 2 main activates worker run 3 main done
Process parameters
The fourth parameter of Start is an address that the process
can read back with MyParam, and UrgencyOf
returns the urgency of a process. In GNU Modula-2 15.2 both are broken.
MODULE params;
FROM Processes IMPORT ProcessId, Start, StopMe, Me, MyParam, UrgencyOf;
FROM Storage IMPORT ALLOCATE;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
TYPE
Job = POINTER TO RECORD
size: INTEGER
END;
VAR
job: Job;
worker: ProcessId;
PROCEDURE Work;
VAR
mine: Job;
BEGIN
mine := MyParam();
IF mine = NIL THEN
WriteString(" worker: parameter is NIL")
ELSE
WriteString(" worker: size "); WriteInt(mine^.size, 0)
END;
WriteLn;
WriteString(" worker: urgency "); WriteInt(UrgencyOf(Me()), 0); WriteLn;
StopMe
END Work;
BEGIN
NEW(job);
job^.size := 42;
Start(Work, 0, 2, job, worker);
WriteString("main: urgency of worker "); WriteInt(UrgencyOf(worker), 0);
WriteLn
END params.
A Parameter is a SYSTEM.ADDRESS, and any pointer
can be assigned to it and back, so the job record travels as a pointer.
The worker should see size 42, but MyParam returns
NIL: Start stores the parameter and then calls
Activate, which overwrites it with NIL.
UrgencyOf returns the urgency of the calling process, not of
the one it is asked about: 2 inside the worker, and 0, the urgency of the
main program, when the main program asks about the worker. Until both
are fixed, pass data through module variables or with
Switch, and keep the urgencies in variables of your own.
$ gm2 -fiso params.mod -o params $ ./params worker: parameter is NIL worker: urgency 2 main: urgency of worker 0
Switching with data
Switch(proc, info) makes the calling process passive and runs
proc, handing it the address in info. When some
process switches back, info holds the address that process
passed. This path to MyParam works.
MODULE squares;
FROM Processes IMPORT ProcessId, Parameter, Create, Switch, Me, MyParam;
FROM Storage IMPORT ALLOCATE;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
TYPE
Number = POINTER TO INTEGER;
VAR
boss, squarer: ProcessId;
n: Number;
info: Parameter;
i: INTEGER;
PROCEDURE Square;
VAR
p: Number;
reply: Parameter;
BEGIN
LOOP
p := MyParam();
p^ := p^ * p^;
reply := p;
Switch(boss, reply)
END
END Square;
BEGIN
boss := Me();
Create(Square, 0, 0, NIL, squarer);
NEW(n);
FOR i := 1 TO 4 DO
n^ := i;
info := n;
Switch(squarer, info);
n := info;
WriteInt(i, 0); WriteString(" squared is "); WriteInt(n^, 0); WriteLn
END
END squares.
The main program saves its own identity from Me, creates a
passive squarer and switches to it with a pointer to a number. The
squarer reads the pointer with MyParam, squares the number in
place and switches back with the same pointer, which arrives in the
main program's info. After a Switch, both sides
are passive except the one that runs, so the two processes alternate
strictly, as two coroutines would, and the scheduler has nothing to
choose.
$ gm2 -fiso squares.mod -o squares $ ./squares 1 squared is 1 2 squared is 4 3 squared is 9 4 squared is 16
Waiting with a semaphore
A semaphore is a counter with a queue of waiting processes.
Claim decrements the counter, or, when it is 0, suspends the
caller until another process calls Release.
Release wakes one waiting process, or increments the counter
when nobody waits. A semaphore created with 0 lets the main program wait
until its processes have finished.
MODULE turns;
FROM Processes IMPORT ProcessId, Start, StopMe, Reschedule;
FROM Semaphores IMPORT SEMAPHORE, Create, Claim, Release;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
VAR
done: SEMAPHORE;
a, b: ProcessId;
PROCEDURE Count(name: ARRAY OF CHAR);
VAR
i: CARDINAL;
BEGIN
FOR i := 1 TO 3 DO
WriteString(name); WriteCard(i, 2); WriteLn;
Reschedule
END
END Count;
PROCEDURE Alpha;
BEGIN
Count("alpha");
Release(done);
StopMe
END Alpha;
PROCEDURE Beta;
BEGIN
Count(" beta");
Release(done);
StopMe
END Beta;
BEGIN
Create(done, 0);
Start(Alpha, 0, 0, NIL, a);
Start(Beta, 0, 0, NIL, b);
WriteString("main waits"); WriteLn;
Claim(done);
Claim(done);
WriteString("both finished"); WriteLn
END turns.
Both processes have urgency 0, the same as the main program, and call
Reschedule after each line. Reschedule is a GNU
addition, not ISO: it asks the scheduler to pick again among the ready
processes of the highest urgency. One might expect alpha and beta to take
turns, but gm2 picked alpha three times in a row, then the main program,
and beta ran only when the main program waited in Claim. ISO
does not say in which order processes of the same urgency run, and gm2's
choice is hard to predict, so a program must not depend on it.
done starts at 0; each process releases it once when it is
finished, and the two Claim calls of the main program return
only after both releases.
$ gm2 -fiso turns.mod -o turns $ ./turns alpha 1 alpha 2 alpha 3 main waits beta 1 beta 2 beta 3 both finished
A race
Without a timer, a process cannot be interrupted in the middle of an update. It can, however, give up control itself, for example by calling a procedure that waits. Two depositors that read a shared balance, yield, and then write it back show what goes wrong.
MODULE race;
FROM Processes IMPORT ProcessId, Start, StopMe, Reschedule;
FROM Semaphores IMPORT SEMAPHORE, Create, Claim, Release;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
balance: INTEGER;
done: SEMAPHORE;
a, b: ProcessId;
PROCEDURE Deposit;
VAR
i, old: INTEGER;
BEGIN
FOR i := 1 TO 5 DO
old := balance;
Reschedule;
balance := old + 10
END;
Release(done);
StopMe
END Deposit;
BEGIN
balance := 0;
Create(done, 0);
Start(Deposit, 0, 0, NIL, a);
Start(Deposit, 0, 0, NIL, b);
Claim(done);
Claim(done);
WriteString("balance "); WriteInt(balance, 0); WriteLn
END race.
Each depositor adds 10 five times, so the balance should be 100. A
depositor reads the balance into old and yields before it
writes old + 10. When the other depositor runs in between, it
reads the same old balance, and one of the two deposits is overwritten.
Three deposits were lost in this run. Here the yield is an explicit
Reschedule; in a real program it is any call that may suspend
the process, such as a Claim or a read from a slow device.
$ gm2 -fiso race.mod -o race $ ./race balance 70
Mutual exclusion
A semaphore created with 1 lets only one process at a time into the code
between Claim and Release, the
critical section. CondClaim claims the semaphore
only when that does not have to wait, so the program can count how often a
depositor found the section taken.
MODULE mutex;
FROM Processes IMPORT ProcessId, Start, StopMe, Reschedule;
FROM Semaphores IMPORT SEMAPHORE, Create, Claim, Release, CondClaim;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteInt;
VAR
balance, waits: INTEGER;
done, lock: SEMAPHORE;
a, b: ProcessId;
PROCEDURE Deposit;
VAR
i, old: INTEGER;
BEGIN
FOR i := 1 TO 5 DO
IF NOT CondClaim(lock) THEN
INC(waits);
Claim(lock)
END;
old := balance;
Reschedule;
balance := old + 10;
Release(lock)
END;
Release(done);
StopMe
END Deposit;
BEGIN
balance := 0; waits := 0;
Create(done, 0);
Create(lock, 1);
Start(Deposit, 0, 0, NIL, a);
Start(Deposit, 0, 0, NIL, b);
Claim(done);
Claim(done);
WriteString("balance "); WriteInt(balance, 0); WriteLn;
WriteString("waits "); WriteInt(waits, 0); WriteLn
END mutex.
The depositors still yield inside the update, but now the other depositor
cannot enter: its CondClaim returns FALSE, it
counts a wait, and its Claim suspends it until the first one
calls Release. The balance is 100. A semaphore used this way
is called a mutex. The critical section should be as short as
possible, because every process that needs it waits.
$ gm2 -fiso mutex.mod -o mutex $ ./mutex balance 100 waits 5
A bounded buffer
A producer and a consumer that share a buffer of fixed size need two semaphores: one counts the free slots, the other the used ones. The producer waits when the buffer is full, the consumer when it is empty.
MODULE buffer;
FROM Processes IMPORT ProcessId, Start, StopMe;
FROM Semaphores IMPORT SEMAPHORE, Create, Claim, Release;
FROM STextIO IMPORT WriteString, WriteLn;
FROM SWholeIO IMPORT WriteCard;
CONST
Size = 3;
Items = 7;
VAR
slots: ARRAY [0..Size-1] OF CARDINAL;
head, tail: CARDINAL;
free, used, done: SEMAPHORE;
producer, consumer: ProcessId;
PROCEDURE Produce;
VAR
i: CARDINAL;
BEGIN
FOR i := 1 TO Items DO
Claim(free);
slots[tail] := i * 10;
tail := (tail + 1) MOD Size;
WriteString("put "); WriteCard(i * 10, 0); WriteLn;
Release(used)
END;
StopMe
END Produce;
PROCEDURE Consume;
VAR
i, value: CARDINAL;
BEGIN
FOR i := 1 TO Items DO
Claim(used);
value := slots[head];
head := (head + 1) MOD Size;
WriteString(" got "); WriteCard(value, 0); WriteLn;
Release(free)
END;
Release(done);
StopMe
END Consume;
BEGIN
head := 0; tail := 0;
Create(free, Size);
Create(used, 0);
Create(done, 0);
Start(Produce, 0, 0, NIL, producer);
Start(Consume, 0, 0, NIL, consumer);
Claim(done);
WriteString("finished"); WriteLn
END buffer.
The buffer has three slots, used as a ring: tail is the next
slot to fill, head the next to empty. free
starts at 3 and used at 0. The producer fills three slots
and blocks on the fourth Claim(free); the consumer then
empties all three and blocks on Claim(used), and so on. Each
Release makes the other side ready, but gm2 keeps running
the process that released, so the output comes in runs of three. No slot is read before it is written, and none is overwritten
before it is read. The main program waits only for the consumer, because
the consumer finishes last.
$ gm2 -fiso buffer.mod -o buffer
$ ./buffer
put 10
put 20
put 30
got 10
got 20
got 30
put 40
put 50
put 60
got 40
got 50
got 60
put 70
got 70
finished
Deadlock
Two processes that each hold one resource and wait for the other's wait forever. This is a deadlock. A copying process takes the disk and then the printer, a printing process takes them in the opposite order.
MODULE deadlock;
FROM Processes IMPORT ProcessId, Start, StopMe;
FROM Semaphores IMPORT SEMAPHORE, Create, Claim, Release;
FROM STextIO IMPORT WriteString, WriteLn;
VAR
disk, printer, ready, done: SEMAPHORE;
a, b: ProcessId;
PROCEDURE Copy;
BEGIN
Claim(disk);
WriteString("copy has the disk"); WriteLn;
Claim(ready);
Claim(printer);
WriteString("copy has both"); WriteLn;
Release(printer); Release(disk);
Release(done);
StopMe
END Copy;
PROCEDURE Print;
BEGIN
Claim(printer);
WriteString("print has the printer"); WriteLn;
Release(ready);
Claim(disk);
WriteString("print has both"); WriteLn;
Release(disk); Release(printer);
Release(done);
StopMe
END Print;
BEGIN
Create(disk, 1); Create(printer, 1);
Create(ready, 0); Create(done, 0);
Start(Copy, 0, 0, NIL, a);
Start(Print, 0, 0, NIL, b);
Claim(done);
Claim(done);
WriteString("both finished"); WriteLn
END deadlock.
In a real program the two processes would collide only now and then. The
semaphore ready forces the unlucky order every time: the
copier takes the disk and waits until the printer process has taken the
printer. Then the copier waits for the printer, the printer process for
the disk, and the main program for done. No process is ready,
and GNU Modula-2 detects this: it stops the program with "deadlock found,
no more processes to run and no interrupts active" and exit status 1.
The usual cure is a fixed order: if every process claims the disk before
the printer, the cycle cannot form.
$ gm2 -fiso deadlock.mod -o deadlock $ ./deadlock copy has the disk print has the printer../../../../src/libgm2/libm2pim/../../gcc/m2/gm2-libs/RTint.mod:733:in Listen has caused deadlock found, no more processes to run and no interrupts active $ echo $? 1
Source
GNU Modula-2: the Processes module
GNU Modula-2: the Semaphores module
In this article we have started processes with Start and
Create, ordered them by urgency, passed data with
Switch, waited for processes with a semaphore, lost and
saved deposits in a race, shared a bounded buffer and run into a
deadlock. Two procedures of Processes, MyParam
after Start and UrgencyOf, are broken in gm2
15.2. The coroutines article covers
the mechanism underneath, and the
stacks, queues and trees
article builds a queue as an abstract data type.
Author
List all Modula-2 tutorials.