GoLang Select statement and time.After()

The select statement is used to choose from multiple send/receive channel operations and it blocks until one of the send/receive operation is ready. In case multiple operations are ready or i,e multiple Goroutines are ready, then one of them is chosen at random.

package main

import (
        “fmt”
        “time”
)
func server1(c chan bool) {
        time.Sleep(2 * time.Second)
        fmt.Println(“Response from Asia region server”)
        c <- true
}
func server2(c chan bool) {
        time.Sleep(3 * time.Second)
        fmt.Println(“Response from Africa region server”)
        c <- true
}

func main() {
        c1 := make(chan bool)
        c2 := make(chan bool)

        go server1(c1)
        go server2(c2)

        select {
        case <-c1:
                fmt.Println(“Response from server1”)
        case <-c2:
                fmt.Println(“Response from server1”)
        }
}

Response from Asia region server
Response from server1

As in above example, lets say you have an application, which depends upon the response from any of the servers, running on different regions of the world. Because of the network-delay and other factors this response time may be different. So you can wait within select and whichever responds first, you can proceed accordingly. Here the output is:-
Response from Asia region server
Response from server1


Use of time.After():—
But in above example, if none of the servers are responding or taking huge time, in that case you can provide a maximum waiting time of lets say 4 secs and come out of the select statement. We can handle it as below.

package main

import (
        “fmt”
        “time”
)

func server1(c chan bool) {
        time.Sleep(150 * time.Second)
        fmt.Println(“Response from Asia region server”)
        c <- true
}
func server2(c chan bool) {
        time.Sleep(100 * time.Second)
        fmt.Println(“Response from Africa region server”)
        c <- true
}

func main() {
        c1 := make(chan bool)
        c2 := make(chan bool)

        go server1(c1)
        go server2(c2)

        select {
        case <-c1:
                fmt.Println(“Response from server1”)
        case <-c2:
                fmt.Println(“Response from server1”)
        case <-time.After(4 * time.Second):
                fmt.Println(“Time Out!.. Waited for 4 seconds”)
        }
}

Time Out!.. Waited for 4 seconds

Here the output will be:–
Time Out!.. Waited for 4 seconds

2 thoughts on “GoLang Select statement and time.After()

Leave a Reply

Your email address will not be published.