make(chan bool)与make(chan bool,1)的行为有何不同?

Mat*_*att 11 channel go

我的问题来自尝试阅读一个频道,如果可以的话,或者如果可以的话,使用一个select声明来写它.

我知道指定的通道make(chan bool, 1)是缓冲的,我的问题的一部分是它之间的区别,并且make(chan bool)- 这个页面所说的是同样的东西make(chan bool, 0)- 一个可以适合0值的通道的点是什么它?

操场A:

chanFoo := make(chan bool)

for i := 0; i < 5; i++ {
    select {
    case <-chanFoo:
        fmt.Println("Read")
    case chanFoo <- true:
        fmt.Println("Write")
    default:
        fmt.Println("Neither")
    }
}
Run Code Online (Sandbox Code Playgroud)

输出:

Neither
Neither
Neither
Neither
Neither
Run Code Online (Sandbox Code Playgroud)

(删除default案例会导致死锁!!)

现在看到游乐场B:

chanFoo := make(chan bool, 1)   // the only difference is the buffer size of 1

for i := 0; i < 5; i++ {
    select {
    case <-chanFoo:
        fmt.Println("Read")
    case chanFoo <- true:
        fmt.Println("Write")
    default:
        fmt.Println("Neither")
    }
}
Run Code Online (Sandbox Code Playgroud)

B输出:

Write
Read
Write
Read
Write
Run Code Online (Sandbox Code Playgroud)

就我而言,B输出就是我想要的.有什么好的无缓冲通道?我在golang.org上看到的所有例子似乎都使用它们一次发送一个信号/值(这是我所需要的) - 但是在游乐场A中,频道永远不会被读取写入.在理解频道时,我在这里错过了什么?

sta*_*ify 11

一个可以在其中容纳0个值的通道的重点是什么

首先,我想指出这里的第二个参数意味着缓冲区大小,因此它只是一个没有缓冲区的通道(非缓冲通道).

实际上,这就是你的问题产生的原因.未缓冲的通道只有在有人阻止从中读取时才可写,这意味着你应该使用一些协同程序 - 而不是这个单独的协同程序.

另请参阅The Go Memory Model:

来自无缓冲通道的接收在该通道上的发送完成之前发生.