How to kill blocking go routine

Issue

So i’m trying to implement a go routine that simply listens on a Redis subscription (I use the Go-redis library for this) and then sends messages
on a channel after it recieves/processes the redis messages.

Something like this:

func foo(redis *redis.Client, comm chan HandlerSignal) {

    ...

    for {
        msg, err := pubsub.ReceiveMessage()
        sig := HandlerSignal{msg}
        comm <- sig
    }
}

But I can’t figure out the best way to tell the go routine to return when it is blocking and waiting for a redis message.

Does anyone know the common practice for this kind of situation or am I going about this all wrong?

Solution

As I can see here: https://github.com/go-redis/redis/blob/v3.2.30/pubsub.go#L253 pubsub.ReceiveMessage() uses internally ReceiveTimeout(5 * time.Second). Why not use the same function (as @Tomasz Kłak suggested)?

func foo(redis *redis.Client, comm chan HandlerSignal, quit chan struct{}) {
    ...
    for {

        select {
        case <-quit:
            return
        default:
            msg, err := pubsub.ReceiveTimeout(5 * time.Second)
            sig := HandlerSignal{msg}
            comm <- sig    
        }
    }
}

Since ReceiveTimeout will block routine for the following 5 seconds, default case will be not saturated.

Answered By – Cedmundo

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.