In this example we are going to create a "ping/pong" game with "buffered" channels. There will be two goroutines which are dedicated to ping and pong the ball every second infinitely. Channels are used for communication among goroutines so in this case two goroutines will inform other once they hit the ball.


Example 1


package main

import (
"fmt"
"time"
)

func main() {
ping := make(chan struct{}, 1)
pong := make(chan struct{}, 1)

ping<- struct{}{}

go play(ping, pong)

time.Sleep(time.Millisecond)
}

func play(ping, pong chan struct{}) {
for {
select {
case <-ping:
fmt.Println("ping")
pong<- struct{}{}
case <-pong:
fmt.Println(" pong")
ping<- struct{}{}
}
}
}

Example 2


package main

import (
"fmt"
"time"
)

func main() {
pingChan := make(chan int, 1)
pongChan := make(chan int, 1)

go ping(pingChan, pongChan)
go pong(pongChan, pingChan)

pingChan <- 1

select {}
}

func ping(pingChan <-chan int, pongChan chan<- int) {
for {
ball := <-pingChan

fmt.Println("Ping", ball)
time.Sleep(1 * time.Second)

pongChan <- ball+1
}
}

func pong(pongChan <-chan int, pingChan chan<- int) {
for {
ball := <-pongChan

fmt.Println("Pong", ball)
time.Sleep(1 * time.Second)

pingChan <- ball+1
}
}

Test


Ping 1
Pong 2
Ping 3
Pong 4
Ping 5
Pong 6
Ping 7
Pong 8
Ping 9
Pong 10
Ping 11
Pong 12
...
...
...