In this example we are going to create a "ping/pong" game with sync mutex package. There will be two goroutines which are dedicated to ping and pong the ball every second infinitely. We don't need them to communicate with each other so no need for channels. Instead, we will use a shared variable and let them access it at a time to avoid conflicts.


Example


package main

import (
"fmt"
"sync"
"time"
)

type Ball struct {
hit int
mux sync.Mutex
}

func (b *Ball) Ping() {
b.mux.Lock()
defer b.mux.Unlock()

b.hit++
fmt.Println("Ping", b.hit)
}

func (b *Ball) Pong() {
b.mux.Lock()
defer b.mux.Unlock()

b.hit++
fmt.Println("Pong", b.hit)
}

func main() {
ball := &Ball{}
for {
ball.Ping()
time.Sleep(1 * time.Second)
ball.Pong()
time.Sleep(1 * time.Second)
}
}

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
...
...
...