英文:
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 "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)
}
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论