tkornblit
tkornblit

Reputation: 31

Golang Channel Maintenance

I'm using go channels as a queue-like mechanism, which has suited me very well. I'm opening up one of these queue-like channels for each user, and have a for-range loop for each one of these channels. The only thing is that I'm not closing any of these channels.

I was wondering if its customary in Go to run a go-routine on a timer that basically destructs inactive channels, almost acting like a "smart" garbage collector.

Any feedback would be appreciated.

Thanks.

Upvotes: 3

Views: 326

Answers (1)

jimt
jimt

Reputation: 26437

It is a common practice to furnish channel reads and writes with a timeout. This is a safeguard which ensures a goroutine stops blocking if a given interval of time has passed.

A use case for this is where you fire up N routines to perform asynchronous searches on various http clients. You will want to wait for results from as many as you can, but you don't want to wait forever. These http fetchers will perform their query and send the result back to you, provided they can accomplish the task within a set timeout.

Here is a simple version of that principle. You can run it on the Go playground. The only difference here is that the goroutine is reading from our queue channel, instead of being the one to send us data. But the principle is identical.

package main

import (
    "fmt"
    "time"
)

func main() {
    queue := make(chan int, 1)
    defer close(queue)

    // Fire up a consumer.
    // Ensure it times out after 3 seconds of waiting for a value.
    go func() {
        select {
        case val := <-queue:
            fmt.Printf("Received: %d\n", val)
        case <-time.After(3 * time.Second):
            fmt.Println("Timeout!")
        }
    }()

    // Do something important for 5 seconds.
    <-time.After(5 * time.Second)

    // Send value to user.
    queue <- 123
}

Upvotes: 3

Related Questions