douguanyan9928 2014-06-28 14:58
浏览 44
已采纳

无缓冲通道

I'm doing the Go Tour: http://tour.golang.org/#72 This is my code:

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

This is the output:

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

As far as I understand channels block when they are passed with values. I expect to see an output like this:

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

Channels are not buffered, is fmt.Println buffered? What happens here? :)

  • 写回答

1条回答 默认 最新

  • dongshi1102 2014-06-28 17:44
    关注

    You're on the right track when you mention fmt.Println. Channel reads and writes are not the only time the scheduler can switch to another goroutine. A blocking system call can also trigger a context switch.

    From the 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 will ultimately call a blocking system call (write()), so that's why you're seeing this behavior.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探