On Wednesday, 8 July 2020 11:17:56 UTC+1, Andrei Tudor Călin wrote:
>
> I think this works for some cases, but it is potentially wasteful (and 
> even leaky) in terms of resource usage.
>
> For example, if ctx is context.Background(), it leaks a goroutine for 
> every connection
>

If this is a network server, that's easily fixed: you make a new ctx for 
each connection (derived from the main one), and cancel it just before the 
connection is closed.  I think it's useful anyway to have a context which 
covers the lifetime of that connection.

>  It also keeps the additional goroutine around for the entire lifetime of 
the connection.

Goroutines are cheap.

How about the following?

type Deadliner interface {
        SetDeadline(t time.Time) error
}

func addContext(ctx context.Context, d Deadliner) {
        go func() {
                <-ctx.Done()
                d.SetDeadline(time.Now())
        }()
}

func handleConnection(ctx context.Context, conn net.Conn) {
    ctx, cancel := context.WithCancel(ctx)
    defer cancel()
    addContext(ctx, conn)

    ... rest of code goes here
}

That seems pretty clean to me.  My only concern is there's a possibility of 
calling SetDeadline on an already-closed connection, and whether that would 
cause a panic.

>

-- 
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/aa0eaf7a-27a8-4dc0-a6d7-245317cc4187o%40googlegroups.com.

Reply via email to