为什么这个程序会产生输出

huangapple go评论72阅读模式
英文:

Why is this program producing output

问题

我是从谷歌学习GO的新手。在这里有一个关于缓冲通道的程序:

package main

import "fmt"
import "time"

func main() {
    c := make(chan int, 2)
    c <- 1
    fmt.Println(<-c)
    time.Sleep(1000 * time.Millisecond)
    c <- 2    
    fmt.Println(<-c)
}

它会产生输出。但是根据http://tour.golang.org/#64上的说明:

> 当缓冲区时,发送到缓冲通道会阻塞。
> 当缓冲区为空时,接收会阻塞。

根据它的说法,它只在时发送,为什么程序会产生输出,而不是在第一条语句中无限等待c被填满?

英文:

I am new to GO from google. In buffered channels here is a program:

package main

import &quot;fmt&quot;
import &quot;time&quot;

func main() {
    c := make(chan int, 2)
    c &lt;- 1
    fmt.Println(&lt;-c)
    time.Sleep(1000 * time.Millisecond)
    c &lt;- 2    
    fmt.Println(&lt;-c)
}

It produces output. But according to http://tour.golang.org/#64 it says:

> Sends to a buffered channel block only when the buffer is full.
> Receives block when the buffer is empty.

As it says it send only when FULL why does the program produce an output instead of waiting infinity for c to full up at the first statement. ?

答案1

得分: 6

你的通道缓冲区大小为2。你放入一个整数,然后取出一个整数。然后你睡眠并重复这个过程。直到你尝试插入第三个整数而没有取出任何整数时,通道才会阻塞。前两个整数将被缓冲。

英文:

Your channel has a buffer size of two. You're putting one int in then pulling one int out. Then you sleep and repeat the process. The channel will not block until you try to insert a third int without pulling any ints out. The first two ints will be buffered.

答案2

得分: 6

我猜你没有正确理解幻灯片。
它说的是“仅阻塞”,你理解成了“仅工作”。

幻灯片上说的是:

  • 如果缓冲区不满,则你的发送操作将正常工作,不会阻塞。

  • 如果缓冲区已满,则你的发送操作将阻塞,直到缓冲区不再满。

所以你的例子按照规定的方式工作。

英文:

I guess you didn't understood the slide properly.
It says "block only" you understood "work only".

What the slide said is:

  • If the buffer is not full, then your send will work properly and it won't block

  • If the buffer is full, then your send will block until the buffer is not full.

So your example is working as specified.

huangapple
  • 本文由 发表于 2013年3月21日 06:20:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/15535920.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定