Volume C1 · Basic concepts · TAOCP Section 1.4.2
Coroutines
Draft. This chapter is written and checked by the tools of the project, and a person has not reviewed it yet. Read it with care.
Read it next to Section 1.4.2 of the book. The nodes and the exercises of the section.
Contents
Coroutines
Overview
A subroutine has a master and a servant: the caller starts it, and it ends when it returns. A coroutine pair has no master. The two routines pass control back and forth, and each of them goes on from the place where it last stopped. The technique fits the work in which data go through several stages, for example a reader that turns cards into characters and a writer that packs the characters into output records. Section 1.4.2 gives the linkage in MIX, which is the linkage of Section 1.4.1 used twice, one time in each direction. It then gives a worked program, the register-saving variant of the linkage, and a comparison between coroutines and programs with several passes.
The section uses the instructions STJ and JMP and the idea of return address of Section 1.4.1. The worked program uses the input and output instructions of Section 1.3.1. This chapter writes its own listing of the worked program, and the simulator that ran it models the card reader and the card punch as devices that are always ready.
The ideas
A coroutine has several exits, and it enters at the last one. Take two routines A and B. When A jumps to B and B later jumps to A, A must not start again at the top, and it must not go to the instruction after the jump in B, since that instruction ran already. A must continue at the instruction after its own last jump to B. So each coroutine needs a cell that holds its resume point, and a jump to the coroutine is a jump through this cell.
The linkage uses two cells and four lines. Each coroutine has an entrance with two instructions: STJ, which stores rJ in the cell of the other coroutine, and a jump through its own cell. Before the first transfer, the own cell of a coroutine jumps to its first instruction. After each transfer, the cell of the coroutine that was left holds the place where it must continue.
Each coroutine can be written as if the other were its subroutine. The writer of the first coroutine writes JMP B at the place where he needs a service from B, and he continues in the next line when control comes back. The same holds for B. The result is that two simple loops cooperate, where one loop that does both jobs would be hard to write.
The register contract is a part of the interface. What a coroutine leaves in the registers when it gives control away, and what it expects when control returns, is a specification as in Section 1.4.1. If the contracts of the two coroutines do not match, the linkage must save the registers that would be lost.
Coroutines are passes that run at the same time. A program with several passes, which each read the output of the pass before, can be written as a chain of coroutines. Data pass from one stage to the next one item at a time, and no storage for the whole stream is needed. The price is that all the stages must be in memory together. A chain of coroutines is not always possible: when a stage needs data from all the input before it can give its first item, or when two stages need each other's answers, the order of the work cannot be that of a pipe.
Definitions, results and proofs
Definition (coroutines, TAOCP Section 1.4.2). Two routines A and B are coroutines when each of them can transfer control to the other, and when each transfer to a routine continues it at the place where it last gave control away, or at its first instruction if it has never given it away. A transfer is a jump that is a call of the other routine.
Node: 1.4.2-def-coroutine · Lean: not yet stated
Explanation. The word equals in the title of this chapter's outline means that neither routine ends when the other one continues. In a subroutine call the callee always starts at its entrance and the caller always continues after the call. In a coroutine transfer both sides behave as the callee: they continue at a place that was saved by an earlier transfer. A chess match is a model, in which each player keeps his own position while the other thinks.
Example. Take a pair that has no purpose except to show the transfers. The coroutine PING adds , and to rI1 in three turns, and it gives control to PONG after each addition. The coroutine PONG adds , and to rI2 in three turns, and it gives control back to PING after each. The program, with the linkage of the next theorem, was run in a simulator of MIX. The table has the state after each transfer. The columns PINGX and PONGX have the address in the cell that is a jump to the coroutine of that name, which is the resume point of the coroutine that is waiting.
| Transfer | Event | Next instruction | rI1 | rI2 | PINGX jumps to | PONGX jumps to |
|---|---|---|---|---|---|---|
| 0 | start | first line of PING at | 0 | 0 | ||
| 1 | PING calls PONG | first line of PONG at | 1 | 0 | ||
| 2 | PONG calls PING | , the line after the first call | 1 | 1 | ||
| 3 | PING calls PONG | , the line after the first call of PONG | 11 | 1 | ||
| 4 | PONG calls PING | 11 | 3 | |||
| 5 | PING calls PONG | 111 | 3 | |||
| 6 | PONG calls PING | 111 | 7 |
The run ends with rI1 and rI2 . The control passes between the two loops six times, and each routine resumes at the line after its own last call. The whole run takes instructions.
Theorem (the linkage of two coroutines, TAOCP eq. 1.4.2(1)). Let A and B be two coroutines in MIX. Let the entrance of A be the pair STJ BX, then AX JMP A1, and let the entrance of B be the pair STJ AX, then BX JMP B1. Here A1 and B1 are the first instructions of the two routines, and the other instructions of A and B call the other routine by JMP B and JMP A. Let the two cells AX and BX be changed only by the two instructions STJ, and let the run start in A1. Then each JMP B in A, when it runs, makes B continue at the place where it last called A, or at B1 if it has not called A before, and A is continued in the same way by a JMP A in B.
Node: 1.4.2-(1) · Lean: not yet stated
The four lines of the linkage are these.
A STJ BX
AX JMP A1
B STJ AX
BX JMP B1
Explanation. The linkage is the linkage of Section 1.4.1 for two subroutines. The difference is that the return cell of the first is the entrance cell of the second. The instruction STJ of B stores the resume point of A in AX, and the instruction JMP in AX is the entrance of A. So the same cell is at the same time the place where A is restarted and the cell that was written by B.
Proof. The proof is by induction on the number of transfers that have run. Let be the address that the cell AX jumps to, and the address of BX, after transfers. The claim is that is the first instruction A1 of A when A has not called B yet, and otherwise the instruction after A's last JMP B. The claim for BX is the same with B1. For the cells are as set, and the claim is true. Suppose the claim holds after transfers, and that the next transfer is a jump from A to B, at the address . The jump sets rJ to . The entrance B stores rJ in AX, so , which is the instruction after the last JMP B of A. The cell BX is not changed, so . Then the instruction JMP in BX jumps to , and by the claim this is the right place for B to continue. The case of a jump from B to A is the same with A and B exchanged. Each transfer is one of the two cases, so the claim holds for all .
Example. In the table of the previous example, transfer 3 is PING's second call of PONG, at . The entrance of PING stored in PINGX. The entrance of PONG did not change PONGX. Control then went through PONGX to , the line after the first call of PONG to PING, and PONG added to rI2, which gave .
Cost. A transfer costs the instruction JMP of the caller, the instruction STJ and the jump in the entrance of the other coroutine, which take , and u. So a transfer takes u, and a round trip takes u. This is the same count as the cost of u for one call of a subroutine in Section 1.4.1.
Algorithms and programs
Program (the worked example, TAOCP Section 1.4.2). The input is a line of characters of the MIX code that ends with a period. A digit in the input is not copied. It means that the next character is repeated times. Other characters are copied. The output is the resulting string, cut into groups of three characters. Each group is a word of bytes with the three characters in the first three bytes. The program has two coroutines. The coroutine EXPAND reads the characters through a subroutine NEXT, applies the digit rule, and passes each character of the result to GROUP. The coroutine GROUP collects the characters and punches a card of groups. The program stops after it has punched the card with the period. This chapter assumes one input card, no blank inside the text, no period right after a digit, only letters as characters that are not digits and not the period, and at most characters in the result.
Node: 1.4.2-prog-example · Lean: not yet stated
Idea. Three routines share the work. The subroutine NEXT gives the next nonblank character of the card. It keeps rI6 as the number of words of the card that were taken, and rX as the part of the current word that was not read yet. A word with only blanks left is zero in rX, so it is skipped without a test of each byte. The coroutine EXPAND keeps in rI5 the number of copies that it still has to send, and in rA the character. The coroutine GROUP keeps in rI4 the index of the output word that it fills. The two coroutines talk through the linkage of the theorem above. The linkage lines are in the middle of the listing, and EXPAND calls GROUP by JMP GROUP and GROUP calls EXPAND by JMP EXPAND.
The input of the run. The input is the line M1N0Q23R. The rule gives these parts: M is copied; the digit with the next character N gives NN; the digit with Q gives Q; the digit with the next character gives 333; R is copied; the period is copied. The result is MNNQ333R. which has characters, so the card has the three groups MNN, Q33 and 3R..
The program. The listing below is written for this chapter. The reader is the card reader, unit , and the punch is unit . The words of the card are at to , and the output words are at to .
START ENT6 16 the card is used up
ENTX 0
JMP GROUP1 start with the coroutine GROUP
NEXT STJ BACK subroutine: next nonblank character in rA
LOOP JXNZ GET characters left in rX?
CMP6 =16=
JL WORD words left on the card?
IN CARD(16) no: read a new card
JBUS *(16)
ENT6 0
WORD LDX CARD,6 take the next word
INC6 1
JMP LOOP
GET ENTA 0
SLAX 1 the first character goes to rA
JAZ LOOP skip a blank
BACK JMP *
EXPAND1 JMP NEXT the coroutine EXPAND
CMPA =30=
JL PASS code below 30: not a digit
CMPA =39=
JG PASS code above 39: not a digit
DECA 29 a digit: rA = n+1
STA T
LD5 T rI5 = n+1
JMP NEXT the character to repeat
JMP SEND
PASS ENT5 1 one copy
SEND JMP GROUP send the character
DEC5 1
J5P SEND
JMP EXPAND1
GROUP STJ ECONT the linkage of the theorem
GCONT JMP GROUP1
EXPAND STJ GCONT
ECONT JMP EXPAND1
GROUP1 ENT4 15 the coroutine GROUP: clear the output words
1H STZ OUTBUF,4
DEC4 1
J4NN 1B
ENT4 0
2H JMP EXPAND get a character
STA OUTBUF,4(1:1)
CMPA PERIOD
JE FLUSH
JMP EXPAND
STA OUTBUF,4(2:2)
CMPA PERIOD
JE FLUSH
JMP EXPAND
STA OUTBUF,4(3:3)
CMPA PERIOD
JE FLUSH
INC4 1
CMP4 =16=
JL 2B next group
FLUSH OUT OUTBUF(17) punch the card
JBUS *(17)
CMPA PERIOD
JNE GROUP1 more cards
HLT
The cell T and the constant PERIOD (the code of the period) are two words in the data area. The name T is a cell for the digit. The two names EXPAND1 and GROUP1 are the first instructions of the two coroutines, and in the linkage they play the role of A1 and B1.
A run. The input card has the text M1N0Q23R. The simulator ran the program and punched one card with the three groups MNN, Q33 and 3R., as the rule says. The run had transfers: calls of GROUP by EXPAND and calls of EXPAND by GROUP. The first call of EXPAND by GROUP came after the clearing of the output words, at time , and the last transfer, which sent the period to GROUP, came at time . The run took u. The table has the transfers for the first four characters, with the state of the two cells at the time of the entrance, after its first instruction STJ.
| Transfer | Entrance | Time | rA (character) | ECONT jumps to | GCONT jumps to |
|---|---|---|---|---|---|
| 1 | EXPAND | 72 | blank | 3017 | 3042 |
| 2 | GROUP | 100 | M | 3029 | 3042 |
| 3 | EXPAND | 109 | M | 3029 | 3046 |
| 4 | GROUP | 146 | N | 3029 | 3046 |
| 5 | EXPAND | 155 | N | 3029 | 3050 |
| 6 | GROUP | 161 | N | 3029 | 3050 |
The address is EXPAND1, the first instruction of the expander, and is the instruction DEC5 after the call JMP GROUP in SEND. The addresses , and are the lines after the three calls JMP EXPAND of the grouping loop. At transfer 1 the grouper asks for its first character, and the expander starts at its first line. At transfer 6 the expander sends the second N without any new reading, since rI5 still held .
Correctness. The proof has three claims, one for each routine, and they are combined by the linkage theorem.
Claim 1, the subroutine NEXT. Let the card text be , with five characters in each word. Call the words . At each entrance to LOOP, rI6 is the number of words of the card taken so far, and rX holds the characters of the word that were not read, shifted to the left, with blanks at the right. The claim is that each call returns the next nonblank character of the text that was not returned before. At the first call, rI6 , so the lines at LOOP see rX and rI6 not less than , and the card is read and rI6 becomes . The load takes , and the loop is entered again. If rX is not zero then some character in it is nonblank, and GET takes its first character with ENTA 0 and SLAX 1. If this character is blank, rA is , JAZ goes back to LOOP, and the rest of rX is examined. Otherwise the character is returned, and rX holds the rest. If rX is zero then all of its characters are blank, and the next word is taken. Since the text has a nonblank period and the period is returned last, the loop ends. The characters come in the order of the text, and no character is returned twice.
Claim 2, the coroutine EXPAND. The claim is that the characters passed to GROUP, in order, are the characters of the string that the rule gives for the text, up to the period. At each entrance to EXPAND1, the characters of the text before the point that NEXT has reached form a complete prefix of items, where an item is a digit with the following character, or one other character. The first character of the next item is returned by the call at EXPAND1. If its code is below or above it is not a digit, rI5 is set to , and the character is sent once. If it is a digit, DECA 29 gives , and LD5 loads the low two bytes of the word T in rI5, so rI5 with . The second call of NEXT gives the character to repeat, and SEND passes it to GROUP, and the loop DEC5 and J5P sends it times in all. Then control goes to EXPAND1 for the next item. Between two sends, EXPAND keeps rI5, rI6 and rX, and the character in rA, but GROUP does not use rI5, rI6 and rX. The register rA, which the loop needs to send the same character again, is changed by GROUP only in the linkage, and GROUP does not change it: its instructions STA, CMPA and OUT leave rA as it is, and so GROUP gives rA back unchanged. This is the point where the specifications of the two coroutines mesh.
Claim 3, the coroutine GROUP. The claim is that the -th character that GROUP receives is stored in the byte of the word of the output area, and that the card is punched when the period arrives. After the clearing loop, the output area is zero, which is blank. The three groups of lines store the characters of one word in the bytes , and , in turn, and after the third character they increase rI4 and go to the next word. After each store they compare with the period. When the character is the period, the control goes to FLUSH and the card is punched with the characters before it and the period, and the rest of the words are blank. The stop is HLT. The case in which is large is excluded by the condition that there are at most characters, which is the capacity of one card.
The combination. Start at START. The coroutine GROUP starts at GROUP1, and its first JMP EXPAND runs the entrance EXPAND, which stores the resume point in GCONT and goes through ECONT to EXPAND1. By the linkage theorem every later JMP EXPAND continues EXPAND at its last call of GROUP, and every later JMP GROUP continues GROUP at its last call of EXPAND. So the characters that EXPAND sends are exactly those that GROUP receives, in the same order, and the three claims give the result.
Time. Let the text have characters, with the period included, and let be the number of words of the card that are read. Let be the number of digits that act as counts, let be the number of letters that are copied, so , and let be the number of characters of the result, with the period included, so for the digits . Let be the number of complete groups before the one with the period. Then the program takes u from the first instruction to the HLT, if every device is ready when it is called. The sum is found by adding the cost of the four parts.
- The start takes u.
- The subroutine NEXT is called times. A call that returns a character costs STJ (), JXNZ (), ENTA (), SLAX (), JAZ () and the return jump (), which is u. A load of a word costs JXNZ (), CMP6 (), JL (), LDX (), INC6 () and JMP (), which is u. The first load also runs IN, JBUS and ENT6, which are u. The sum for NEXT is .
- The expander has one cycle for each letter, one for each digit with its character, and one for the period. A letter costs JMP NEXT (), CMPA (), JL () and ENT5 (), which is u. The period has the code , so it costs JMP NEXT, CMPA, JL, CMPA, JG and ENT5, which is u. A digit costs JMP NEXT, CMPA, JL, CMPA, JG, DECA, STA, LD5, JMP NEXT and JMP SEND, which is u. Each of the copies costs the call JMP GROUP ( u). The pair DEC5 and J5P ( u) runs after every copy except the last one, since the run stops inside GROUP. Each cycle except the last ends with JMP EXPAND1 ( u), which is times. The sum is .
- The linkage runs times, with STJ and JMP at u each time. The sum is .
- The grouper costs u for the clearing, and u for each of the characters (JMP EXPAND, STA, CMPA, JE, which are ). Each of the complete groups before the last adds INC4, CMP4 and JL, which are u. The flush costs OUT, JBUS, CMPA, JNE and HLT, which are u. The sum is .
The total is . With this becomes .
Example. For the text M1N0Q23R. the values are , , (M and R), , and . The formula gives , which is the time of the run. The formula was also compared with the simulator on random inputs, with up to characters in the result, and it agreed in every case.
Program (a linkage that saves register A, TAOCP eq. 1.4.2(4)). When a coroutine needs register A to be unchanged between its transfer and its return, the linkage of the theorem is changed in this way: the entrance of B stores rA in a cell HOLDA, and the entrance of A loads rA from HOLDA before the jump through AX. The entrance of B is therefore STJ AX, then STA HOLDA, then BX JMP B1, and the entrance of A is STJ BX, then LDA HOLDA, then AX JMP A1.
Node: 1.4.2-(4) · Lean: not yet stated
The two entrances in full are these.
A STJ BX
LDA HOLDA
AX JMP A1
B STJ AX
STA HOLDA
BX JMP B1
Explanation. The change keeps the values of the theorem on the cells, and it adds the two instructions that save and restore a register. The same idea is used for a subroutine in Section 1.4.1. It costs u for a round trip from A to B and back.
Example. Let A put in rA and call B. Let B put in rA and call A. With the linkage of the theorem, when A continues, rA is . With the linkage above, B's entrance stores the value , and A's entrance loads it, so rA is again. The two programs were run. The program with the plain linkage had in the cell where A stored its register, and took u. The program with the saving linkage had and took u, which is u more.
Proof. By the theorem, the transfers resume the coroutines at the right places. Consider a call of B by A. The entrance of B runs STA HOLDA first, after STJ, so HOLDA gets rA as A had it. Nothing changes HOLDA before A is entered again, since only the two instructions that save and restore access it. When B calls A, the entrance of A runs LDA HOLDA, so rA is A's value. Between the two, B may change rA as it likes. The saving of B's register is not provided, and when B resumes, rA has the value that A had when it called.
Remark (coroutines and passes, TAOCP Section 1.4.2). A program of several passes, each of which reads the whole output of the pass before it, can be replaced by a chain of coroutines when each pass reads its input in the order in which it was written and never sends information back to a pass before it. The chain gives the same output. It has different costs from the passes: it saves the time and the space of the intermediate data, and it needs the programs of all the passes in memory together. A task in which the first item of output needs all of the input, or in which two stages talk in both directions, cannot be put in the form of passes.
Node: 1.4.2-informal-multipass · Lean: not yet stated
Explanation. The worked example is a case. It could be done in two passes: EXPAND writes the characters of the result to a medium, and GROUP reads them from it. The coroutine version has no medium, and the two ways differ in three points: the passes are easier to design one by one, a pass chain needs time and room for the intermediate data, and a chain of coroutines needs room for all the code at once.
Example. A count for the worked program shows the time difference when the medium is the memory. In the worked program each character costs two calls ( u each) and two entrances ( u each), which is u. A two-pass version with an array of words stores each character with STA and an index update and reads it with LDA and an index update, which is u. The array is cheaper by u for each character. The gain of the coroutines is the space: the two-pass version needs words for the array. If the medium is a tape, each word costs the time of writing and reading on the tape, and this time is the dominant cost. The advantage of coroutines grows with the cost of the medium.
Proof of the first statement. Let pass 1 produce the sequence and pass 2 consume it in the same order. Pass 2 is a function of the sequence read so far. In the coroutine chain, EXPAND passes the element to GROUP at the -th transfer. By the linkage theorem GROUP resumes with the same state that pass 2 has after it has read , and the state of EXPAND is the state of pass 1 after it has written . Both programs are deterministic, so by induction on the sequences and the final outputs agree.
A task that is not a chain. Take the task of printing each of numbers divided by their sum. The first number printed depends on every input number, so any program must read all numbers before it prints the first. A chain of coroutines cannot give the numbers to the printer before the sum is known, so it needs a store of all numbers. It has no advantage over a program of two passes.
The exercises
The table has the exercises of Section 1.4.2. The book marks no exercise of this section as recommended in the text that C1 reads. The kind is the class of spec 06.3 that C1 proposes.
| Exercise | Rating | Markers | Kind | Lean | Solution |
|---|---|---|---|---|---|
| 1.4.2-1 | 10 | informal | not yet stated | X1, 1.4.2-1 | |
| 1.4.2-2 | 20 | K3 | not yet stated | X1, 1.4.2-2 | |
| 1.4.2-3 | 20 | K2 | not yet stated | X1, 1.4.2-3 | |
| 1.4.2-4 | 20 | K6 | not yet stated | X1, 1.4.2-4 | |
| 1.4.2-5 | 15 | K6 | not yet stated | X1, 1.4.2-5 | |
| 1.4.2-6 | 22 | K6 | not yet stated | X1, 1.4.2-6 | |
| 1.4.2-7 | 30 | K6 | not yet stated | X1, 1.4.2-7 |
Exercise 1 asks why short examples of coroutines are hard to find. The answer is in the remark on passes: a coroutine pair earns its place only when the data flow is long enough to make a pass chain costly, and such a task is rarely short. Exercises 2 and 3 are about details of the book's own program. Their method is the same for any pair: follow the two resume cells through the first transfers, as in the tables above, and ask what each cell holds when a given instruction runs. Exercises 4 and 6 ask for the linkage on other machines and for three coroutines. The theorem and its proof carry over, with one resume cell for each coroutine. Exercise 5 is solved by the saving linkage above, and exercise 7 is a program in the style of the worked example.
Lean
The Lean code of tamnd/taocp-lean at main has the model of MIX in TAOCP/MIX/ and the program logic in TAOCP/MIX/Logic/, and it has no file for Section 1.4.2. The linkage of coroutines is made of the instruction STJ and a jump, which are in TAOCP.MIX.State.execStore and TAOCP.MIX.State.jump. The theorem of the linkage is a statement about the memory cells AX and BX after each transfer, and it would be a family of triples of the logic of TAOCP/MIX/Logic/Hoare.lean, one for each transfer. The worked program would need a model of the devices of MIX with their input and output words, which the Lean model does not have yet. The Node lines of this section therefore have no Lean name. The handbook states the formula for the time of the worked program as a result of the simulation of this chapter, and it does not state it as a theorem of Lean.
Notes and history
The term coroutine comes from Melvin Conway, who described the idea in his paper Design of a Separable Transition-Diagram Compiler, Communications of the ACM 6 (1963), pages 396 to 408. The linkage of this section is the one that a MIX programmer can write with the tools of Section 1.4.1: two subroutine linkages that are tied together, so that each routine returns into the other.
Coroutines came into languages of the ALGOL family with the Simula languages. The book of Dahl, Dijkstra and Hoare, Structured Programming (1972), has examples of coroutines. A chain of coroutines resembles a pipeline of programs, as in a command that connects the output of one program to the input of the next. The stages in the middle are called filters.
Section 1.4.2 treats two routines that call each other as equals. Each one continues where it stopped when the other gives control back. The section gives the three-line linkage for two coroutines in MIX, a worked program with a reader, an expander of digit codes and a writer that groups the output in triples, and a discussion of the link between coroutines and programs of several passes. This chapter proves the linkage, builds a complete test program with its own listing, derives its running time as a formula that a simulator confirmed on many inputs, and weighs coroutines against passes.
The source of this page. Something is wrong? Report it.