Sleep()和同步之间是否存在关联?

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

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 (
	&quot;fmt&quot;
)

func pinger(c chan string) {
	for i := 0; ; i++ {
		c &lt;- &quot;ping&quot;
	}
}

func ponger(c chan string) {
	for i := 0; ; i++ {
		c &lt;- &quot;pong&quot;
	}
}

func printer(c chan string) {
	for {
		msg := &lt;-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(&amp;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中检索值之前,函数pingerponger无法向通道发送值(也就是说,pinger和ponger在你从printer函数中读取之前一直在等待向通道发送值)。

因此,在你的示例中,通过Sleep函数引入了时间延迟,以便从通道c中读取值。

这就是为什么你可以通过Sleep函数实现漂亮而缓慢的读取效果的原因 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 &lt;- 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 Sleep()和同步之间是否存在关联?

huangapple
  • 本文由 发表于 2017年7月9日 00:47:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/44988530.html
匿名

发表评论

匿名网友

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

确定