Why a single go routine with sleep is using 100% cpu (1 core)

1,493 views
Skip to first unread message

Sagar P.

unread,
Sep 11, 2016, 7:11:26 PM9/11/16
to golang-nuts
go version
go version go1.6.3 linux/amd64

uname -r
3.13.0-95-generic

Below code is using 100% cpu (1 full core)

package main

import (
    "fmt"
    "os"
    "time"
)


func main() {
    channel := make(chan bool, 1)
    go doSomething(channel)
    for {
        select {
            case <-channel:
                fmt.Println("Go routine has ended")
                os.Exit(0)

            default:
        }
    }
}

func doSomething(ch chan bool) {
    time.Sleep(60000 * time.Millisecond)
    ch <- true
}

Please let me know if you what is happening above.

Chris Hines

unread,
Sep 11, 2016, 7:22:13 PM9/11/16
to golang-nuts, saga...@gmail.com
The for loop in func main busy loops because the default clause of the select statement will never block. Delete the default clause and the program will sleep quietly then exit.

Sagar P.

unread,
Sep 11, 2016, 8:01:17 PM9/11/16
to golang-nuts, saga...@gmail.com
Ah, I see my mistake. Removed default to avoid a busy-loop.

Thanks!

Ilya Kostarev

unread,
Sep 11, 2016, 8:52:16 PM9/11/16
to golan...@googlegroups.com

On 09/12/2016 03:01 AM, Sagar P. wrote:
Ah, I see my mistake. Removed default to avoid a busy-loop.

Thanks!

Without `default` you need hot `for` and `select` at all. Just
    _ = <-channel:

    fmt.Println("Go routine has ended")
     os.Exit(0)
would be enough. In real situations however  `default` most likely be an essence. CPU load is a cost of `select` which is quite expensive operation.

__
Ilya Kostarev
Reply all
Reply to author
Forward
0 new messages