On Saturday, 25 January 2020 22:16:26 UTC, Eric Raymond wrote:
>
>
> And that's the insight that led be to the extension I proposed. I asked 
> myself what the most natural way to pass out a soft close might be.
>  
>

Suppose we continue with the idea of an iterator being a goroutine which 
stuffs values down a channel, like https://tour.golang.org/concurrency/4

It occurs to me that the idiomatic way to signal termination and cleanup is 
with a Context.  Suppose "for ... range" acted on a function which returned 
two values: a channel of arbitrary type T, and a cancel function.

It would iterate over the values on T, but when the for loop terminates 
(either normally or abnormally) would call the cancel function.  That's 
basically the pattern from https://tour.golang.org/concurrency/5

Prototype: https://play.golang.org/p/rU7sulJqxaE

When playing with this, I found of course that after cancelling the 
context, the cleanup in the goroutine happened asynchronously (it's a 
goroutine, after all).  That would be fine in many cases - but it's also 
possible to make the cleanup synchronous by wrapping the cancel function so 
that it waits for the goroutine to exit.

Version with synchronous cleanup: https://play.golang.org/p/hsYqU_jaViI

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/9fae3d58-ac58-4908-929f-38a236a93227%40googlegroups.com.

Reply via email to