The following code executes a function as a goroutine. It works fine on Windows 10, but it does not appear that the goroutine executes on Ubuntu 15.10.
package main
import (
"log"
"time"
)
func main() {
go StartSomething()
log.Println("Some program now running.")
for {
}
}
func StartSomething() {
for {
log.Println("I have been started.")
time.Sleep(2 * time.Second)
}
}
I’m programming from my laptop on Windows 10 with go1.5.1 windows/amd64 and deploying the application to my VM which is running Ubuntu 15.10 Wily (checked that it’s up to date) and go1.5.1 linux/amd64. At first, I thought my problem was platform specific, but after ruling that out, I tried to replicate the issue in a more simple form (as seen above).
Indeed, select{} is a better way to block forever in Go than for{}. To bring some closure to the topic, however, it may be worthwhile to understand why for{} prevented the other goroutine from running; and my hunch is that the Ubuntu VM that @vivace was using had only one virtual CPU.
If my hunch is correct, then Go 1.5.1 would default GOMAXPROCS to 1. In that case, once the for {} loop started, it would never yield the CPU to the other goroutine. The Windows 10 laptop, however, probably has more than one core, which could cause the Go runtime to run the for{} loop and the goroutine on separate threads, allowing both to make progress.
As an addition:
If you plan to let it run in a console, I prefer fmt.Scanln() if you just want to start it and let it run - also gives the opportunity for a more “graceful” shutdown instead of Ctrl-C (eg cleanup after running).
As I understand it, which may not be 100% correct, GC needs to be able to stop all goroutines. That can’t happen with the for loop so the program should deadlock at first GC, regardless of GOMAXPROCS.