concurrency - Ordering of senders in a Go channel -


consider ping pong example http://www.golang-book.com/10/index.htm#section2.

package main  import (     "fmt"     "time" )  func pinger(c chan string) {     := 0; ; i++ {         c <- "ping"     } }  func ponger(c chan string) {     := 0; ; i++ {         c <- "pong"     } }  func printer(c chan string) {     {         msg := <- c         fmt.println(msg)         time.sleep(time.second * 1)     } }  func main() {     var c chan string = make(chan string)      go pinger(c)     go ponger(c)     go printer(c)      var input string     fmt.scanln(&input) } 

the authors write:

"the program take turns printing ping , pong."

however, true, go must decide on order in senders can send channel? otherwise, there no guarantee ping sent before pong (i.e. can't 2 pings, or 2 pongs in row). how work?

there no synchronization between ping , pong goroutines, therefore there no guarantee responses print in order.

if force goroutines race gomaxprocs>1, random output:

pong ping ping pong ping pong ping pong pong 

this isn't example of "ping-pong", since there's no call , response.


Comments

Popular posts from this blog

node.js - Mongoose: Cast to ObjectId failed for value on newly created object after setting the value -

gradle error "Cannot convert the provided notation to a File or URI" -

python - NameError: name 'subprocess' is not defined -