duanjianlu0506 2015-05-21 18:25
浏览 20
已采纳

主线程永不屈服于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?

  • 写回答

1条回答 默认 最新

  • duanshangying5102 2015-05-21 18:29
    关注

    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(…).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥60 pb数据库修改或者求完整pb库存系统,需为pb自带数据库
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路