dongxiong1935 2012-04-10 20:10 采纳率: 0%
浏览 38
已采纳

了解goroutines

I'm trying to understand concurrency in Go. In particular, I wrote this thread-unsafe program:

package main

import "fmt"

var x = 1

func inc_x() { //test
  for {
    x += 1
  }
}

func main() {
  go inc_x()
  for {
    fmt.Println(x)
  }
}

I recognize that I should be using channels to prevent race conditions with x, but that's not the point here. The program prints 1 and then seems to loop forever (without printing anything more). I would expect it to print an infinite list of numbers, possibly skipping some and repeating others due to the race condition (or worse -- printing the number while it is being updated in inc_x).

My question is: Why does the program only print one line?

Just to be clear: I'm not using channels on purpose for this toy example.

  • 写回答

4条回答 默认 最新

  • douping1825 2012-04-10 21:24
    关注

    There are a few things to keep in mind about Go's goroutines:

    1. They are not threads in the sense of Java's or C++ threads
    2. The go runtime multiplexes the goroutines across the system threads
      • the number of system threads is controlled by an environment variable GOMAXPROCS and defaults to 1 currently I think. This may change in the future
    3. The way goroutines yield back to their current thread is controlled by several different constructs
      • the select statement can yield control back to the thread
      • sending on a channel can yield control back to the thread
      • doing IO operations can yield control back to the thread
      • runtime.Gosched() explicitly yields control back to the thread

    The behavior you are seeing is because the main function never yields back to the thread and is instead involved in a busy loop and since there is only one thread the main loop has no place to run.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容