Files
bl/logic/service/fight/start_test.go

71 lines
1.3 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package fight
import (
"fmt"
"sync"
"time"
)
// 记录A、B是否完成的标志
var (
aFinished bool
bFinished bool
mu sync.Mutex // 保护标志位的互斥锁
)
// 当A 战斗准备完成
func onAFinished() {
fmt.Println("A已完成触发onAFinished")
checkBothFinished() // 检查是否两者都完成
}
// 当B 战斗准备完成
func onBFinished() {
fmt.Println("B已完成触发onBFinished")
checkBothFinished() // 检查是否两者都完成
}
// 当A和B都 这时候给双方回复开始战斗包
func onBothFinished() {
fmt.Println("A和B都已完成触发onBothFinished")
}
// 检查A和B是否都完成若都完成则调用onBothFinished
func checkBothFinished() {
mu.Lock()
defer mu.Unlock()
if aFinished && bFinished {
onBothFinished()
}
}
// 模拟A的执行
func doA() {
fmt.Println("A开始执行...")
time.Sleep(2 * time.Second) // 模拟耗时操作
mu.Lock()
aFinished = true
mu.Unlock()
onAFinished() // A完成后调用
}
// 模拟B的执行
func doB() {
fmt.Println("B开始执行...")
time.Sleep(3 * time.Second) // 模拟耗时操作
mu.Lock()
bFinished = true
mu.Unlock()
onBFinished() // B完成后调用
}
func main() {
// 启动A和B的执行
go doA()
go doB()
// 等待一段时间,避免主程序提前退出
time.Sleep(4 * time.Second)
}