ZetCode

Tcl coroutines

last modified November 24, 2026 Tcl 8.6

A coroutine is a procedure that can suspend itself and later continue from the same point, with all its local variables intact. Tcl 8.6 introduced this mechanism with the coroutine, yield and yieldto commands. Coroutines make generators, data pipelines and cooperative tasks possible without threads or callbacks.

This article starts with a single suspended procedure and builds up to a three-stage pipeline. Each example is a complete script that can be run with tclsh.

coroutine and yield basics

The coroutine name command ?arg...? command creates a new command called name and runs command immediately. Execution continues until the body calls yield; at that point the coroutine is suspended and the value given to yield becomes the result of coroutine. Calling the coroutine command later resumes the body, and yield returns the value passed to that call.

basics.tcl
proc worker {} {
    puts "step one"
    yield
    puts "step two"
}

coroutine job worker
puts "main is running"
job
puts "job finished"

coroutine job worker runs worker up to the yield, prints step one, and returns control to the main script. The later job call resumes the procedure after the yield and prints step two. The procedure is never restarted, so any local state would still be there.

$ tclsh basics.tcl
step one
main is running
step two
job finished

A generator

A generator is a coroutine that produces a sequence of values on demand. The loop counter lives in the coroutine, so the caller does not need a temporary list and the values can be computed one at a time. The creation call itself produces the first value, because the body runs until the first yield.

generator.tcl
proc numbers {n} {
    for {set i 1} {$i <= $n} {incr i} {
        yield $i
    }
}

set value [coroutine gen numbers 3]
while {$value ne ""} {
    puts "got $value"
    set value [gen]
}
puts "generator exhausted"

The assignment to value captures the 1 that the coroutine yields during creation. Each gen call resumes the loop and returns the next number. When the loop ends, numbers returns, the gen command is deleted, and the final call returns the empty string, which stops the loop.

$ tclsh generator.tcl
got 1
got 2
got 3
generator exhausted

Passing values into a coroutine

Values also travel in the other direction. When a suspended coroutine is resumed, its pending yield returns the argument of the resume call. A coroutine can therefore keep state and react to each new input, which is the basis of an accumulator, a parser or a state machine.

passing.tcl
proc adder {} {
    set total 0
    while 1 {
        set value [yield $total]
        if {$value eq "stop"} {
            return $total
        }
        incr total $value
    }
}

coroutine acc adder
puts "start: [acc 0]"
puts "add 5: [acc 5]"
puts "add 7: [acc 7]"
puts "total: [acc stop]"

acc 0 resumes the first yield, which returns 0; the loop adds it and yields the total. The next calls pass 5 and 7, and each result is the running sum. acc stop returns the total from the procedure, which also deletes the coroutine command.

$ tclsh passing.tcl
start: 0
add 5: 5
add 7: 12
total: 12

yieldto and switching between coroutines

yieldto command ?arg...? suspends the current coroutine and transfers control directly to another command, which runs at once. The switching coroutine is not resumed until something calls its command again; at that point yieldto returns the list of arguments given to that call. Because every coroutine has a command, two coroutines can hand control back and forth.

yieldto.tcl
proc stage1 {} {
    puts "stage1 starts"
    set reply [yieldto two "data"]
    puts "stage1 resumes with: $reply"
}

proc stage2 {} {
    set item [yield]
    puts "stage2 received: $item"
    yieldto one "stage2 done"
}

coroutine two stage2
coroutine one stage1
puts "back in main"
rename two {}

Creating two first suspends it at its plain yield. Creating one runs stage1, which hands the item to two; stage2 prints it and hands control back to one, whose yieldto returns the list {stage2 done}. When stage1 returns, the main script continues. Coroutine two is still suspended at its own yieldto, so the example deletes it with rename; the last section covers that in detail.

$ tclsh yieldto.tcl
stage1 starts
stage2 received: data
stage1 resumes with: {stage2 done}
back in main

A producer and a consumer

Coroutines make a clean pull-based producer and consumer pair. The consumer asks the source for one item at a time, and the source computes the next item only when it is asked. The initial yield in the producer lets the coroutine be created before the first value is requested.

producer.tcl
proc lines {n} {
    yield
    for {set i 1} {$i <= $n} {incr i} {
        yield [format "row %d" $i]
    }
}

proc consume {source} {
    while {[set row [$source]] ne ""} {
        puts "consumer got $row"
    }
    puts "consumer done"
}

coroutine source lines 3
consume source

The creation call stops at the first yield and returns an empty string, which is ignored. consume then pulls three rows and stops when the source returns. No list of rows is ever built: the coroutine holds the loop counter and produces each row on demand.

$ tclsh producer.tcl
consumer got row 1
consumer got row 2
consumer got row 3
consumer done

A pipeline of coroutines

A pipeline chains several coroutines, each with the command of the previous stage as its upstream. A stage pulls a value, transforms it and yields the result, so one call at the end of the chain produces one item. The initial yield in every stage allows the whole chain to be assembled before the first value flows.

pipeline.tcl
proc numbers {n} {
    yield
    for {set i 1} {$i <= $n} {incr i} {
        yield $i
    }
}

proc double {upstream} {
    yield
    while 1 {
        set value [$upstream]
        if {$value eq ""} {
            return
        }
        yield [expr {$value * 2}]
    }
}

proc label {upstream} {
    yield
    set count 0
    while 1 {
        set value [$upstream]
        if {$value eq ""} {
            return
        }
        incr count
        yield [format "%d. value %d" $count $value]
    }
}

coroutine src numbers 3
coroutine dbl double src
coroutine out label dbl

while {[set line [out]] ne ""} {
    puts $line
}

numbers produces 1, 2 and 3, double multiplies each value by two, and label adds a line number. When the source is exhausted, its empty result travels back through the stages, each stage returns, and the final call returns an empty string. The pipeline is then gone.

$ tclsh pipeline.tcl
1. value 2
2. value 4
3. value 6

Cleanup and the coroutine command lifetime

A coroutine command behaves like any other command. As soon as its body returns or raises an error, the command is deleted and can no longer be called. A suspended coroutine, on the other hand, keeps its stack and variables alive until it is resumed or explicitly removed with rename. Inside a coroutine, info coroutine returns its own command name.

lifetime.tcl
proc ticker {} {
    yield "first"
    yield "second"
    return "third"
}

set name [coroutine t ticker]
puts "created: $name"
puts "next:    [t]"
puts "next:    [t]"
puts "commands: [info commands t]"

proc sleeper {} {
    puts "running as [info coroutine]"
    while 1 {
        yield
    }
}

coroutine nap sleeper
puts "commands: [info commands nap]"
rename nap {}
puts "commands: [info commands nap]"

The creation call returns first and the two later calls return second and third. After the third call the t command is gone, so info commands prints nothing. The second coroutine is suspended forever; rename nap {} deletes it, which also runs any deletion traces on its variables.

$ tclsh lifetime.tcl
created: first
next:    second
next:    third
commands: 
running as ::nap
commands: nap
commands: 

Source

The coroutine manual page describes the commands and the rules for resuming and switching. The info, proc and apply pages cover the pieces that coroutines are built from.

This article covered the coroutine lifecycle, generators, two-way value passing, yieldto, a producer and consumer pair, a pipeline and cleanup. The Tcl proc command page explains the procedure syntax used by every coroutine body, and Tcl info command covers info coroutine and the other introspection commands.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.