一个用Golang同步突变的乒乓例子

106 阅读1分钟

在这个例子中,我们将用同步互斥包创建一个 "乒乓 "游戏。将有两个goroutines专门用于每秒无限次地击球和乒乓。我们不需要它们之间的通信,所以不需要通道。相反,我们将使用一个共享变量,让它们每次访问它以避免冲突。

例子

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

测试

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