V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
martinmo
V2EX  ›  编程

求教 goroutine 切换时间点的问题

  •  
  •   martinmo · 2019-05-16 10:08:10 +08:00 · 3428 次点击
    这是一个创建于 1779 天前的主题,其中的信息可能已经有所发展或是发生改变。

    最近在看 GO 语言,在 gotour 的示例里面加了几个输入,但输出序列本人无法理解,想求教下各位大佬: 源码: package main

    import "fmt"
    
    func fibonacci(c, quit chan int) {
    	x, y := 0, 1
    for {
    	select {
    	case c <- x:
    		fmt.Printf("a%v\n",x)
    		x, y = y, x+y
    	case <-quit:
    		fmt.Printf("quit")
    		return
    	}
    }
    }
    
    func main() {
    c := make(chan int)
    quit := make(chan int)
    go func() {
    	for i := 0; i < 10; i++ {
    		fmt.Println("b")
    		fmt.Println(<-c)
    	}
    	quit <- 0
    }()
    fibonacci(c, quit)
    }
    
    输出序列:
    b
    0
    b
    a0
    a1
    1
    b
    1
    b
    a1
    a2
    2
    b
    3
    b
    a3
    a5
    5
    b
    8
    b
    a8
    a13
    13
    b
    21
    b
    a21
    a34
    34
    quit
    

    疑问: 1.x 第一次输入到 c 中时,从输出序列上看,fibonacci 所在 goroutine 被中断,是否是一旦接受到输入,处于读取等待的 goroutine 立即被唤起并运行?

    2.如果 [ 1 ] 所述正确的话,输出 a0 之后怎么接着输入 a1,而不是 1?

    1 条回复    2019-05-16 14:35:52 +08:00
    martinmo
        1
    martinmo  
    OP
       2019-05-16 14:35:52 +08:00
    应该是尽量让当前 goroutine 往前执行,如果管道对方的数据刚好准备好的,就获取 /写管道,然后继续执行直至管道那边没有数据,然后中断,转让执行权给另一个 goroutine。按这个思路可以解释得通对应的输出。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5407 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 07:01 · PVG 15:01 · LAX 00:01 · JFK 03:01
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.