Sleep statement between go statements

Issue

I saw the below setup in a code base today. Does the Sleep() function have any effect? I suppose it’s there to guarantee that serverA is running before serverB starts, but since execution of both may be deferred until later, this is not really guaranteed, right?

func main() {

    go util.Execute("run", serverA)

    time.Sleep(time.Millisecond * 500)

    go util.Execute("run", serverB)

    for {
        log.Println("running")
        time.Sleep(time.Second * 30)
    }
}

Solution

It does have an effect that it will wait 500 ms before the next goroutine will attempt to run and start serverB. And you’re correct that it’s not really guaranteed that serverA will completely start within that time.

A better strategy would be to check for some kind of signal from serverA that it is fully running, but not knowing anything about what type of server that is it would be hard to advise.

Answered By – Turnkey

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.