You can't generally cancel a running coroutine easily. You can of course do
rename runningCoro ""
But then:
::chan event $chan readable [list [info coroutine]]
just like say coroutine::util gets does, then that event will produce an error. Unfortunately I found no way to handle coroutine cancellation without resorting to callbacks. The good news is one can do
proc cleanup {args} {...} proc coro {} { ... trace add command [info coroutine] delete [list cleanup $arg1 $arg2] ... }
Which will allow it to e.g. unsubscribe from fileevent. Quite awkward: another proc has to be created and it also has too accept mostly args that trace passes to it in addition to any useful args we may pass from inside the coro.
To sum up, here's one particular solution I could come up with:
package require coroutine::util #let's say it's C for cancellable or coroutine namespace eval cio {} proc cio::gets {args} { set chan [lindex $args 0] trace add command [info coroutine] delete [list cio::gets.cleanup] } proc cio::gets.cleanup {chan args} { ::chan event $chan readable {} }
This will not cause background errors should its caller be destroyed during the call. It's still sub-optimal: no error is raised in the caller, and if it wants to do some of its own cleanup, it's going to have to schedule other callbacks. Callbacks are harder to reason about than something like
proc coro {} { if {catch {imaginary_cancellable_gets $chan} err} { if {$err eq "cancelled"} { <cleanup> } } }
would be. But that's not possible to do with the current tcl coro mechanism, is it?