ankush981
ankush981

Reputation: 5417

Is there a relation between Sleep() and synchronization?

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?

Upvotes: 0

Views: 69

Answers (1)

jeevatkm
jeevatkm

Reputation: 4791

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

Upvotes: 1

Related Questions