How does make(chan bool) behave differently from make(chan bool, 1)?

拈花ヽ惹草 提交于 2019-11-30 08:52:42

what is the point of a channel that can fit 0 values in it

First I want to point out that the second parameter here means buffer size, so that is simply a channel without buffers (un-buffered channel).

Actually that's the reason why your problem is generated. Un-buffered channels are only writable when there's someone blocking to read from it, which means you shall have some coroutines to work with -- instead of this single one.

Also see The Go Memory Model:

A receive from an unbuffered channel happens before the send on that channel completes.

Unbuffered channels (created without capacity) will block the sender until somebody can read from them, so to make it work as you expect, you should use two goroutines to avoid the deadlock in the same thread.

For example, with this code: http://play.golang.org/p/KWJ1gbdSqf

It also includes a mechanism for the main func to detect when both goroutines have finished.

package main

import "fmt"

func send(out, finish chan bool) {
    for i := 0; i < 5; i++ {
        out <- true
        fmt.Println("Write")
    }
    finish <- true
    close(out)
}

func recv(in, finish chan bool) {

    for _ = range in {
        fmt.Println("Read")
    }
    finish <- true

}

func main() {
    chanFoo := make(chan bool)
    chanfinish := make(chan bool)

    go send(chanFoo, chanfinish)
    go recv(chanFoo, chanfinish)

    <-chanfinish
    <-chanfinish
}

It won't show the alternate Read and Write, because as soon as send writes to the channel, it is blocked, before it can print the "Write", so the execution moves to recv that receives the channel and prints "Read". It will try to read the channel again but it will be blocked and the execution moves to send. Now send can write the first "Write", send to the channel (without blocking because now there is a receiver ready) and write the second "Write". In any case, this is not deterministic and the scheduler may move the execution at any point to any other running goroutine (at least in the latest 1.2 release).

An unbuffered channel means that read and writes from and to the channel are blocking.

In a select statement:

  • the read would work if some other goroutine was currently blocked in writing to the channel
  • the write would work if some other goroutine was currently blocked in reading to the channel
  • otherwise the default case is executed, which happens in your case A.
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!