The precise ordering of things is a bit non-deterministic at the fringe. If 
precise ordering really matters (maybe for cancelling a stream like this, it 
doesn’t, sometimes it does), a default case in the select statement is really 
useful, and it also matters what DoSomething does.
________________________________
From: golang-nuts@googlegroups.com <golang-nuts@googlegroups.com> on behalf of 
Torsten Bronger <bron...@physik.rwth-aachen.de>
Sent: Monday, December 19, 2022 1:52:36 AM
To: golang-nuts@googlegroups.com <golang-nuts@googlegroups.com>
Subject: [go-nuts] Context cancellation: Is it sufficient to make long-running 
things interruptible?

Hallöchen!

The context documentation gives this example:

    // Stream generates values with DoSomething and sends them to out
    // until DoSomething returns an error or ctx.Done is closed.
    func Stream(ctx context.Context, out chan<- Value) error {
        for {
                v, err := DoSomething(ctx)
                if err != nil {
                        return err
                }
                select {
                case <-ctx.Done():
                        return ctx.Err()
                case out <- v:
                }
        }
    }

What if the channel “out” is drained very efficiently?  Then, an
arbitrary number of loop iterations could happen before a
cancellation is detected, couldn’t it?

I would additionally check for ctx.Err() != nil somewhere in the
loop.  Or is there a reason why this is not necessary?

Regards,
Torsten.

--
Torsten Bronger

--
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/87zgbj7maj.fsf%40physik.rwth-aachen.de.

-- 
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/CO2PR07MB2583C50EEB5E02993AE86792A0E59%40CO2PR07MB2583.namprd07.prod.outlook.com.

Reply via email to