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条)

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错