drhzc64482 2018-09-29 16:34
浏览 12

Gosched之外还有什么?

Code snippet below,

package main

import (
        "fmt"
        "runtime"
)

func main() {
        runtime.GOMAXPROCS(1)
        var s string
        done := make(chan bool)
        go func() {
                fmt.Scanln(&s)
                fmt.Println(s)
                done <- true
        }()

        var i int
        for i = 0; i < 1e10; i++ {
        }
        fmt.Println(i)
        <-done
}

Run it, quickly type a few chars e.g. abcd before the for loop ends; finally hit Enter. To my knowledge there is none of yield points available within the for loop for Gosched to switch the main goroutine to the subroutine, why had it promptly printed abcd even before the for loop was finished?

abcd10000000000

abcd
  • 写回答

2条回答 默认 最新

  • dua55014 2018-09-29 16:59
    关注

    It is random you cannot predict the output. Because in your case the go routine will run and then the for loop will execute. Now if go routine finished before the for loop completes its iterations then it will print the value inside the go routine first and send the value on done channel and then it will print the value of i. The done channel will wait until the value is sent on it by the go routine.

    For example if you try to scan only as and then enter fast your value will print first inside the go routine then 10000000000 will print in the last so it depends on if go routine will execute before the for loop completes.

    The runtime can allocate more threads than the value of GOMAXPROCS to service multiple outstanding I/O requests. GOMAXPROCS only affects how many goroutines can actually execute at once; arbitrarily more may be blocked in system calls.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值