3 ms·
Yup! This is exactly how context.WithCancel is implemented; <-ctx.Done() is the signal that everything that cares about cancellation listens on. The returned
by jrockway 2y ago
Yup! This is exactly how context.WithCancel is implemented; <-ctx.Done() is the signal that everything that cares about cancellation listens on. The returned CancelFunc just does `close(thatChannel)`.
I prefer explicitly using contexts for cancellation, but in a pinch:
c := make(chan struct{})
foo(c)
bar(c)
close(c)
is a useful pattern. (I do this a lot in tests that involve concurrency; the test calls t.Cleanup(func() { close(c) }) and then if the test fails with t.Fatal or something, all background work is killed.)
- mappu 2y agoExactly right. These "done channels" were extremely widely used as a doneCh parameter before contexts were introduced in 1.7.