Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Yep this is a utility function in sure thousands have written, including myself. It's not in std which is weird but go had been a bit inconsistent since context was a big api change.

Fun fact: that func has a hidden bug, if one should be pedantic. Can you spot it?



> Fun fact: that func has a hidden bug, if one should be pedantic. Can you spot it?

Are you referring to the fact that the timer is still hanging around? Would this be the most-correct version?

    func sleepCtx(ctx context.Context, delay time.Duration) {
            t := time.NewTimer(delay)
            defer func() {
                    if !t.Stop() {
                            <-t.C
                    }
            }()
            select {
            case <-ctx.Done():
            case <-t.C:
            }
    }


[Weird, I remember already replying to this comment.]

Yes that's what I was thinking of :)

I'm a bit unsure what's the value in draining the channel (which is internal to this func), given that Go should garbage collect channel (and in this case perhaps even some escape analysis).

EDIT: Ah they aren't just closing the channel, but sending a time.Time. That makes sense, the timer wouldn't have anyone to send to if it's unbuffered.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: