On Sun, Apr 4, 2021 at 6:13 AM Sam Whited <s...@samwhited.com> wrote:
>
> In a library I have a `func(context.Context, net.Conn)' (more or less,
> https://godoc.org/mellium.im/xmpp#NewSession). The context is used
> throughout the function to eg. break out of loops, gets passed into
> other functions, etc. and the conn is read from. If the user creates and
> passes in a context with a deadline and also sets a deadline on the
> conn, should I also cancel reads/writes from the conn when the context
> is expired, or allow the user the maximum flexibility of setting their
> own deadline on both?
>
> I've asked this elsewhere (and am copying it here to reach a wider
> audience) and the responses I've gotten seem to fall into:
>
> - The user might have set a deadline on the conn already and overriding
>   it defies user expectations, and
> - The user expects that when the context is canceled the function stops
>   blocking, so you have to cancel any reads/writes on the conn too
>   otherwise the function could keep blocking, defying user expectation
>
> I've gone back and forth a couple of times on how I'd expect this to
> behave and I couldn't find any obvious examples in the standard
> library that would suggest there's a convention so I'd love to get
> other opinions.

My opinion is that when you are using a context, then when the context
is cancelled the operation should also be cancelled.  This doesn't
change if the connection happens to have a separately specified
deadline.  The point of a context is to cancel an operation, so if
there is a context, it should be honored.

Speaking more broadly, while a context is often a deadline, it can
also be cancelled for other reasons (via ctx.WithCancel).  Those other
reasons can include things like "we no longer need this data."  So
that is an argument for why the context should be honored even if
there is a deadline.

Ian

-- 
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/CAOyqgcV5Gm3iparasPZT2FiuaUMOfs3CXu3gLZpoyxTHqGvh-g%40mail.gmail.com.

Reply via email to