dongniaoli1822 2017-07-08 16:47
浏览 37
已采纳

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

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条回答 默认 最新

  • duanke6057 2017-07-08 19:51
    关注

    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 :)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于知识的学以致用的解释
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败