Exercise · Volume 1 · 1.4.2-4
Exercise 1.4.2-4
not stated yet in Lean solution written
| Rating | 20 |
|---|---|
| Kind | K6, write a program: write a MIX or MMIX program from the written solution |
| Section | Section 1.4.2 of Volume 1. Companion chapter: Coroutines |
The task
Show coroutine linkage like (1) for computers that you know.
The exact wording is in your copy of the book.
Hints
Open one hint at a time. Try the exercise again after each.
Hint 1
The linkage of (1) has two parts that you need on any machine: a place where each routine keeps its resume address, and a jump to that place.
Hint 2
A machine that does not let you change instructions needs a data cell for each resume address and an indirect jump.
Solution
Show the solution
Today the code of a program is not changed, so each resume address is kept in a data cell and the jump is indirect. Let AX and BX be the cells for the resume addresses of A and B. At the start AX holds the address A1 and BX holds B1.
On a machine with a link register, here RISC-V. A coroutine calls the other with jal ra, B.
A: la t1, BX Entry to A, called by B.
sw ra, 0(t1) B must resume at the return address.
la t1, AX
lw t0, 0(t1)
jr t0 Go to where A left off.
B: la t1, AX
sw ra, 0(t1)
la t1, BX
lw t0, 0(t1)
jr t0
On a machine whose call instruction puts the return address on a stack, here x86-64, the return address is moved from the stack into the cell:
A: pop qword ptr [BX]
jmp qword ptr [AX]
B: pop qword ptr [AX]
jmp qword ptr [BX]
The stack is balanced, because each switch has one call that pushes an address and one pop that takes it away. It is the same idea as STJ BX in (1). The cell AX has taken the place of the instruction JMP A1 that the MIX program changes.
Check
The scheme is the one of (1) with the instruction word replaced by an address cell. Hand trace. At the start AX holds A1 and BX holds B1. A jumps to B at the point A2, so the call puts A2+1 in the link register or on the stack. Entry B moves it into AX and goes to BX, that is B1. Later B calls A at B2. Entry A moves B2+1 into BX and goes to AX, which now holds A2+1. A goes on after its call, and the next call of B resumes at B2+1. This is what the text shows for (1). The lines were not run on the real machines.
Remarks
Languages with generators, such as Python, give this switching as a feature. Each yield is the jump and the saved frame holds the resume address.
This solution is drafted, and a person has not reviewed it yet. The source.
In Lean
not stated yet The exercise is not stated in Lean yet.
The status is computed from the Lean build. The node of the map.
Something is wrong? Report it.