2 '\" Copyright (c) 2009 Donal K. Fellows.
4 '\" See the file "license.terms" for information on usage and redistribution
5 '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
7 .TH coroutine n 8.6 Tcl "Tcl Built-In Commands"
8 .\" The -*- nroff -*- definitions below are for supplemental macros used
9 .\" in Tcl/Tk manual entries.
11 .\" .AP type name in/out ?indent?
12 .\" Start paragraph describing an argument to a library procedure.
13 .\" type is type of argument (int, etc.), in/out is either "in", "out",
14 .\" or "in/out" to describe whether procedure reads or modifies arg,
15 .\" and indent is equivalent to second arg of .IP (shouldn't ever be
16 .\" needed; use .AS below instead)
19 .\" Give maximum sizes of arguments for setting tab stops. Type and
20 .\" name are examples of largest possible arguments that will be passed
21 .\" to .AP later. If args are omitted, default tab stops are used.
24 .\" Start box enclosure. From here until next .BE, everything will be
25 .\" enclosed in one large box.
28 .\" End of box enclosure.
31 .\" Begin code excerpt.
36 .\" .VS ?version? ?br?
37 .\" Begin vertical sidebar, for use in marking newly-changed parts
38 .\" of man pages. The first argument is ignored and used for recording
39 .\" the version when the .VS was added, so that the sidebars can be
40 .\" found and removed when they reach a certain age. If another argument
41 .\" is present, then a line break is forced before starting the sidebar.
44 .\" End of vertical sidebar.
47 .\" Begin an indented unfilled display.
50 .\" End of indented unfilled display.
53 .\" Start of list of standard options for a Tk widget. The manpage
54 .\" argument defines where to look up the standard options; if
55 .\" omitted, defaults to "options". The options follow on successive
56 .\" lines, in three columns separated by tabs.
59 .\" End of list of standard options for a Tk widget.
61 .\" .OP cmdName dbName dbClass
62 .\" Start of description of a specific option. cmdName gives the
63 .\" option's name as specified in the class command, dbName gives
64 .\" the option's name in the option database, and dbClass gives
65 .\" the option's class in the option database.
68 .\" Print arg1 underlined, then print arg2 normally.
71 .\" Print arg1 in quotes, then arg2 normally (for trailing punctuation).
74 .\" Print an open parenthesis, arg1 in quotes, then arg2 normally
75 .\" (for trailing punctuation) and then a closing parenthesis.
77 .\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
81 .\" # Start an argument description
85 . ie !"\\$2"" .TP \\n()Cu
90 \&\\$1 \\fI\\$2\\fP (\\$3)
103 .\" # define tabbing values for .AP
106 .if !"\\$1"" .nr )A \\w'\\$1'u+3n
109 .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
110 .nr )C \\n()Bu+\\w'(in/out)'u+2n
112 .AS Tcl_Interp Tcl_CreateInterp in/out
113 .\" # BS - start boxed text
114 .\" # ^y = starting y location
122 .if n \l'\\n(.lu\(ul'
125 .\" # BE - end boxed text (draw box now)
130 .ie n \l'\\n(^lu\(ul'
132 .\" Draw four-sided box normally, but don't draw top of
133 .\" box if the box started on an earlier page.
135 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
138 \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
145 .\" # VS - start vertical sidebar
146 .\" # ^Y = starting y location
147 .\" # ^v = 1 (for troff; for nroff this doesn't matter)
151 .ie n 'mc \s12\(br\s0
154 .\" # VE - end of vertical sidebar
162 \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
169 .\" # Special macro to handle page bottom: finish off current
170 .\" # box/sidebar if in box/sidebar mode, then invoked standard
171 .\" # page bottom macro.
178 .\" Draw three-sided box if this is the box's first page,
179 .\" draw two sides but no top otherwise.
180 .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
181 .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
184 .nr ^x \\n(^tu+1v-\\n(^Yu
185 \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
198 .\" # DS - begin display
204 .\" # DE - end display
210 .\" # SO - start of list of standard options
212 'ie '\\$1'' .ds So \\fBoptions\\fR
213 'el .ds So \\fB\\$1\\fR
214 .SH "STANDARD OPTIONS"
220 .\" # SE - end of list of standard options
225 See the \\*(So manual entry for details on the standard options.
227 .\" # OP - start of full description for a single option
232 Command-Line Name: \\fB\\$1\\fR
233 Database Name: \\fB\\$2\\fR
234 Database Class: \\fB\\$3\\fR
238 .\" # CS - begin code excerpt
244 .\" # CE - end code excerpt
249 .\" # UL - underline word
253 .\" # QW - apply quotation marks to word
255 .ie '\\*(lq'"' ``\\$1''\\$2
256 .\"" fix emacs highlighting
257 .el \\*(lq\\$1\\*(rq\\$2
259 .\" # PQ - apply parens and quotation marks to word
261 .ie '\\*(lq'"' (``\\$1''\\$2)\\$3
262 .\"" fix emacs highlighting
263 .el (\\*(lq\\$1\\*(rq\\$2)\\$3
265 .\" # QR - quoted range
267 .ie '\\*(lq'"' ``\\$1''\\-``\\$2''\\$3
268 .\"" fix emacs highlighting
269 .el \\*(lq\\$1\\*(rq\\-\\*(lq\\$2\\*(rq\\$3
271 .\" # MT - "empty" string
276 '\" Note: do not modify the .SH NAME line immediately below!
278 coroutine, yield, yieldto \- Create and produce values from coroutines
281 \fBcoroutine \fIname command\fR ?\fIarg...\fR?
282 \fByield\fR ?\fIvalue\fR?
284 \fByieldto\fR \fIcommand\fR ?\fIarg...\fR?
285 \fIname\fR ?\fIvalue...\fR?
291 The \fBcoroutine\fR command creates a new coroutine context (with associated
292 command) named \fIname\fR and executes that context by calling \fIcommand\fR,
293 passing in the other remaining arguments without further interpretation. Once
294 \fIcommand\fR returns normally or with an exception (e.g., an error) the
295 coroutine context \fIname\fR is deleted.
297 Within the context, values may be generated as results by using the
298 \fByield\fR command; if no \fIvalue\fR is supplied, the empty string is used.
299 When that is called, the context will suspend execution and the
300 \fBcoroutine\fR command will return the argument to \fByield\fR. The execution
301 of the context can then be resumed by calling the context command, optionally
302 passing in the \fIsingle\fR value to use as the result of the \fByield\fR call
304 the context to be suspended. If the coroutine context never yields and instead
305 returns conventionally, the result of the \fBcoroutine\fR command will be the
306 result of the evaluation of the context.
309 The coroutine may also suspend its execution by use of the \fByieldto\fR
310 command, which instead of returning, cedes execution to some command called
311 \fIcommand\fR (resolved in the context of the coroutine) and to which \fIany
312 number\fR of arguments may be passed. Since every coroutine has a context
313 command, \fByieldto\fR can be used to transfer control directly from one
314 coroutine to another (this is only advisable if the two coroutines are
315 expecting this to happen) but \fIany\fR command may be the target. If a
316 coroutine is suspended by this mechanism, the coroutine processing can be
317 resumed by calling the context command optionally passing in an arbitrary
318 number of arguments. The return value of the \fByieldto\fR call will be the
319 list of arguments passed to the context command; it is up to the caller to
320 decide what to do with those values.
322 The recommended way of writing a version of \fByield\fR that allows resumption
323 with multiple arguments is by using \fByieldto\fR and the \fBreturn\fR
327 proc yieldm {value} {
328 \fByieldto\fR return -level 0 $value
333 The coroutine can also be deleted by destroying the command \fIname\fR, and
334 the name of the current coroutine can be retrieved by using
335 \fBinfo coroutine\fR.
336 If there are deletion traces on variables in the coroutine's
337 implementation, they will fire at the point when the coroutine is explicitly
338 deleted (or, naturally, if the command returns conventionally).
340 At the point when \fIcommand\fR is called, the current namespace will be the
341 global namespace and there will be no stack frames above it (in the sense of
342 \fBupvar\fR and \fBuplevel\fR). However, which command to call will be
343 determined in the namespace that the \fBcoroutine\fR command was called from.
346 This example shows a coroutine that will produce an infinite sequence of
347 even values, and a loop that consumes the first ten of them.
358 \fBcoroutine\fR nextNumber allNumbers
359 for {set i 0} {$i < 10} {incr i} {
360 puts "received [\fInextNumber\fR]"
365 In this example, the coroutine acts to add up the arguments passed to it.
368 \fBcoroutine\fR accumulator apply {{} {
371 incr x [\fByield\fR $x]
374 for {set i 0} {$i < 10} {incr i} {
375 puts "$i -> [\fIaccumulator\fR $i]"
379 This example demonstrates the use of coroutines to implement the classic Sieve
380 of Eratosthenes algorithm for finding prime numbers. Note the creation of
381 coroutines inside a coroutine.
384 proc filterByFactor {source n} {
385 \fByield\fR [info coroutine]
387 set x [\fI$source\fR]
393 \fBcoroutine\fR allNumbers apply {{} {while 1 {\fByield\fR [incr x]}}}
394 \fBcoroutine\fR eratosthenes apply {c {
399 set c [\fBcoroutine\fR prime$n filterByFactor $c $n]
402 for {set i 1} {$i <= 20} {incr i} {
403 puts "prime#$i = [\fIeratosthenes\fR]"
408 This example shows how a value can be passed around a group of three
409 coroutines that yield to each other:
412 proc juggler {name target {value ""}} {
414 set value [\fByield\fR [info coroutine]]
416 while {$value ne ""} {
417 puts "$name : $value"
418 set value [string range $value 0 end-1]
419 lassign [\fByieldto\fR $target $value] value
422 \fBcoroutine\fR j1 juggler Larry [
423 \fBcoroutine\fR j2 juggler Curly [
424 \fBcoroutine\fR j3 juggler Moe j1]] "Nyuck!Nyuck!Nyuck!"
427 .SS "DETAILED SEMANTICS"
429 This example demonstrates that coroutines start from the global namespace, and
430 that \fIcommand\fR resolution happens before the coroutine stack is created.
433 proc report {where level} {
434 # Where was the caller called from?
435 set ns [uplevel 2 {namespace current}]
436 \fByield\fR "made $where $level context=$ns name=[info coroutine]"
439 report outer [info level]
441 namespace eval demo {
443 report inner [info level]
445 proc makeExample {} {
446 puts "making from [info level]"
447 puts [\fBcoroutine\fR coroEg example]
453 Which produces the output below. In particular, we can see that stack
454 manipulation has occurred (comparing the levels from the first and second
455 line) and that the parent level in the coroutine is the global namespace. We
456 can also see that coroutine names are local to the current namespace if not
457 qualified, and that coroutines may yield at depth (e.g., in called
462 made inner 1 context=:: name=::demo::coroEg
465 apply(n), info(n), proc(n), return(n)