gpt4 book ai didi

go - 无缓冲 channel

转载 作者:IT王子 更新时间:2023-10-29 02:17:15 24 4
gpt4 key购买 nike

我正在进行 Go Tour:http://tour.golang.org/#72这是我的代码:

package main

import (
"code.google.com/p/go-tour/tree"
"fmt"
)

// Walk walks the tree t sending all values
// from the tree to the channel ch.
func Walk(t *tree.Tree, ch chan int) {
var makeWalk func(t *tree.Tree, ch chan int)

makeWalk = func(t *tree.Tree, ch chan int) {
if t.Left != nil {
makeWalk(t.Left, ch)

}
fmt.Println("-->", t.Value)
ch <- t.Value
fmt.Println("continue here")
if t.Right != nil {
makeWalk(t.Right, ch)
}
}
makeWalk(t, ch)
close(ch)
}

// Same determines whether the trees
// t1 and t2 contain the same values.
func Same(t1, t2 *tree.Tree) bool {
// var ch_l chan int = make(chan int)
// var ch_r chan int = make(chan int)
return false
}

func main() {
ch := make(chan int)
go Walk(tree.New(1), ch)
for i := range(ch) {
fmt.Println(i)
}
}

这是输出:

--> 1
continue here
--> 2
1
2
continue here
--> 3
continue here
--> 4
3
4
continue here
--> 5
continue here
--> 6
5
6
continue here
--> 7
continue here
--> 8
7
8
continue here
--> 9
continue here
--> 10
9
10
continue here

据我所知, channel 在传递值时会阻塞。我希望看到这样的输出:

--> 1
1
continue here
--> 2
2
continue here
...
--> 10
10
continue here

channel 没有缓冲,fmt.Println 有缓冲吗?这里发生了什么? :)

最佳答案

当您提到 fmt.Println 时,您就走在了正确的轨道上。 channel 读取和写入并不是调度程序可以切换到另一个 goroutine 的唯一时间。阻塞系统调用也可以触发上下文切换。

来自FAQ :

When a coroutine blocks, such as by calling a blocking system call, the run-time automatically moves other coroutines on the same operating system thread to a different, runnable thread so they won't be blocked.

fmt.Println 最终会调用阻塞系统调用 (write()),所以这就是您看到此行为的原因。

关于go - 无缓冲 channel ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24468052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com