Version 0 of coroutine is the new main

Updated 2016-04-17 14:11:51 by pooryorick

coroutines and the event loop are a powerful combination. Together they allow multiple control flows to run in a single interpreter and to cooperate to achieve the objective of the program. In a Tcl script, it's a good idea to place the main script into a procedure, and many programmers are in the habit of doing something like this:

proc main {argv0 argv} {
    # The main script
}
main $argv0 $argv

As coroutines take deeper root in the Tcl ecosystem, if third-party commands can assume they're called in a coroutine context, they can take advantage of that fact to yield from the coroutine at opportune moments, allowing other activities in the system to continue on in the meantime. This development will be in large part transparent to the script that considers itself the only control flow in the program. All that's required to use such third-party commands is that the main script be structured like this:

after 0 [list coroutine main apply [list {argv0 argv} {
    # the main script
    exit 0 
} [namespace current]] $argv0 $argv]
vwait ::nameofsomevariablethatwillneverexist

See Also

update considered harmful
Wisdom on working in a concurrent world. coroutines can help avoid the issue of entering the event loop multiple times, but the issue of critical sections is one the programmer will need pay careful attention to in order to maintain sanity.