锁
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
// myAccount 表示我的银行账户余额
var myAccount int
// getAccount 模拟读取数据库中我的账户余额
func getAccount() int {
// 随机休眠0~1秒,模拟从数据库读取数据花费的时间
time.Sleep(time.Duration((float64)(time.Second) * rand.Float64()))
return myAccount
}
// setAccount 模拟更新数据库中我的账户余额
func setAccount(account int) {
// 随机休眠0~1秒,模拟将数据写入数据库花费的时间
time.Sleep(time.Duration((float64)(time.Second) * rand.Float64()))
myAccount = account
}
// trade 模拟对我的账号发起一笔交易,income为正表示收入,为负表示支出
func trade(income int, wg *sync.WaitGroup) {
// 读取我的账户余额
account := getAccount()
// 更新我的账户余额
setAccount(account + income)
wg.Done()
}
func main() {
var waitGroup sync.WaitGroup
for i := 0; i < 10; i++ {
myAccount = 50000
// 添加两个计数器
waitGroup.Add(2)
// 收入6000元
go trade(6000, &waitGroup)
// 支出500元
go trade(-500, &waitGroup)
waitGroup.Wait()
fmt.Println(myAccount)
}
}
最后更新于