What does an empty select do?
An empty select{}
statement blocks forever. It is similar to an empty for{}
statement.
On most (all?) supported Go architectures, the empty select will yield CPU. An empty for-loop won't, i.e. it will "spin" on 100% CPU.
On Mac OS X, in Go, for { }
will cause the CPU% to max, and the process's STATE will be running
select { }
, on the other hand, will not cause the CPU% to max, and the process's STATE will be sleeping
The empty select
statement just blocks the current goroutine.
As for why you'd do this, here is one reason. This snippet is equivalent
if *serve != "" {
fmt.Fprintln(os.Stderr, "httptest: serving on", s.URL)
s.Config.Serve(s.Listener)
} else {
go s.Config.Serve(s.Listener)
}
It's better in that there isn't a wasted goroutine. It's worse in that now there is code repetition. The author optimized for less code repetition over a wasted resource. Note however the permanently block goroutine is trivial to detect and may have zero cost over the duplicating version.