主线程永不屈服于goroutine

  • edit * -- uncomment the two runtime lines and change Tick() to Sleep() and it works as expected, printing one number every second. Leaving code as is so answer/comments make sense.

go version go1.4.2 darwin/amd64

When I run the following, I never see anything printed from go Counter().

package main

import (
  "fmt"
  "time"
  //"runtime"
)

var count int64 = 0

func main() {
  //runtime.GOMAXPROCS(2)
  fmt.Println("main")
  go Counter()
  fmt.Println("after Counter()")
  for {
    count++
  }
}

func Counter() {
  fmt.Println("In Counter()")
  for {
    fmt.Println(count)
    time.Tick(time.Second)
  }
}

> go run a.go
main
after Counter()

If I uncomment the runtime stuff, I will get some strange results like the following all printed at once (not a second apart):

> go run a.go
main
after Counter()
In Counter()
10062
36380
37351
38036
38643
39285
39859
40395
40904
43114

What I expect is that go Counter() will print whatever count is at every second while it is incremented continuously by the main thread. I'm not so much looking for different code to get the same thing done. My question is more about what is going on and where am I wrong in my expectations? The second results in particular don't make any sense, being printed all at once. They should never be printed closer than a second apart as far as I can tell, right?

There is nothing in your tight for loop that lets the Go scheduler run. The schedule considers other goroutines whenever one blocks or on some (which? all?) function calls.

Since you do neither the easiest solution is to add a call to runtime.Gosched. E.g.:

for {
    count++
    if count % someNum == 0 {
        runtime.Gosched()
    }
}

Also note that writing and reading the same variable from different goroutines without locking or synchronization is a data race and there are no benign data races, your program could do anything when reading a value as it's being written. (And synchronization would also let the Go scheduler run.)

For a simple counter you can avoid locks by using atomic.AddInt64(&var, 1) and atomic.LoadInt64(&var).

Further note (as pointed out by @tomasz and completely missed by me), time.Tick doesn't delay anything, you may have wanted time.Sleep or for range time.Tick(…).