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.

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

报告相同问题?

悬赏问题

  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan