英文:
Is there a relation between Sleep() and synchronization?
问题
考虑以下演示通道的程序:
package main
import (
"fmt"
)
func pinger(c chan string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func ponger(c chan string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func printer(c chan string) {
for {
msg := <-c
fmt.Println(msg)
//time.Sleep(time.Second * 1)
}
}
func main() {
var c = make(chan string)
go pinger(c)
go ponger(c)
go printer(c)
var input string
fmt.Scanln(&input)
}
如果我取消注释time.Sleep
调用,输出将以一种好的、可预测的方式交替出现"ping"和"pong"。然而,添加注释会使顺序变得不可预测。作为一个Go的新手,我想知道是什么使得这种同步成为可能。为什么添加等待时间会使得通道的其余部分按顺序执行?
英文:
Consider the following program demonstrating channels:
package main
import (
"fmt"
)
func pinger(c chan string) {
for i := 0; ; i++ {
c <- "ping"
}
}
func ponger(c chan string) {
for i := 0; ; i++ {
c <- "pong"
}
}
func printer(c chan string) {
for {
msg := <-c
fmt.Println(msg)
//time.Sleep(time.Second * 1)
}
}
func main() {
var c = make(chan string)
go pinger(c)
go ponger(c)
go printer(c)
var input string
fmt.Scanln(&input)
}
If I uncomment the time.Sleep
call, the output is "ping" and "pong" taking turns in a nice, predictable manner. However, adding the comment makes the order unpredictable. I'm a Go novice and wondering what enabled this synchronization. Why does adding a wait time make the rest of the channel feeder tow the line?
答案1
得分: 1
Sleep()函数和同步之间有关系吗?
同步是在值被发送到通道和从通道中检索出来之间发生的。
var c = make(chan string)
通道c
一次只能保存一个类型为string的值。在从通道c
中检索值之前,函数pinger
和ponger
无法向通道发送值(也就是说,pinger和ponger在你从printer函数中读取之前一直在等待向通道发送值)。
因此,在你的示例中,通过Sleep函数引入了时间延迟,以便从通道c
中读取值。
这就是为什么你可以通过Sleep函数实现漂亮而缓慢的读取效果的原因
英文:
> Is there a relation between Sleep() and synchronization?
>
> NO
Synchronization happens between value sent to channel and retrieve from channel.
var c = make(chan string)
Channel c
can hold one value of type string at a time. Until the value is retrieve from channel <- c
; function pinger
, ponger
cannot send value to channel c
(i.e. pinger and ponger is waiting to send value to channel till the time you read from printer function).
So in your example, you introduced the time delay via Sleep
func to read the value from channel c
on printer function.
That's why you get nice and slow read with the help of Sleep
func
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论