Golang Channel Service

I use go-channels as a queue-like mechanism that I really liked. I open one of these similar channels in turn for each user, and for each of these channels there is a loop for the range. The only thing is that I do not close any of these channels.

I was wondering if it’s customary for Go to run a timer routine that basically destroys inactive channels, almost acting like a “smart” garbage collector.

Any feedback would be appreciated.

Thank.

+3
source share
1 answer

It is common practice to provide time-out channels for reading and writing. This is a guarantee that ensures that goroutine will stop blocking if a given time interval is passed.

- , N http-. , , . HTTP , .

. Go playground. , , , . .

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
}
+3

All Articles