How to do nothing when the channel is not ready for reading?

Take this example from GoTour, as it illustrates my problem with handling SDL events only when there are events.

package main

import (
"fmt"
"time"
)

func main() {
tick := time.Tick(1e8)
boom := time.After(5e8)
for {
    select {
    case <-tick:
        fmt.Println("tick.")
    case <-boom:
        fmt.Println("BOOM!")
        return
    default:
        fmt.Println("    .")
        time.Sleep(5e7)
    }
}
}

It works. But what if I don't want to print or sleep in the default case, but just want to continue the loop? I tried this:

    case <-boom:
        fmt.Println("BOOM!")
        return
    default: // Nothing here.
    }
}
}

but it blocks.

I saw here and there a proposal for planning goroutines, but I did not understand them. Therefore, I have two questions:

1) Why is it blocked?

2) How to make it do nothing without blocking?

+5
source share
1 answer

Your original example creates this

    .
    .
tick.
    .
    .
tick.
    .
    .
tick.
    .
    .
tick.
    .
    .
tick.
BOOM!

Wheraeas your second example creates this

[process took too long]

, default. default , select . , ( ), . , . , . IO, .

for {
    select {
        // whatever
        default:
    }
}

. -, -, . runtime.Gosched(). run runtime runtime.GOMAXPROCS(2), .

- . , case. ( ), goroutine - !

, , , .

+5

All Articles