背景:学校开学,3位同学要买票回校上课了,就有了这样一个购票程序,当然,实际情况复杂的多,本文仅供参考。
package main import ( "fmt" "sync" ) type Train struct { station map[string]int mu sync.Mutex } func NewTrain() *Train { return &Train{station: map[string]int{}} } func (train *Train) Add(name string, ticket int) { train.mu.Lock() defer train.mu.Unlock() train.station[name] = ticket } func (train *Train) Buy(name string, ticket int) bool { train.mu.Lock() defer train.mu.Unlock() if train.station[name] == 0 || train.station[name] - ticket < 0 { return false } train.station[name] = train.station[name] - ticket return true } func main() { train := NewTrain() train.Add("郑州", 100) train.Add("许昌", 50) train.Add("漯河", 20) train.Add("驻马店", 50) train.Add("信阳", 30) var wg sync.WaitGroup wg.Add(3) go func() { defer wg.Done() ticket := 15 own := train.Buy("信阳", ticket) fmt.Printf("张三购票:%d,状态:%t\n", ticket, own) }() go func() { defer wg.Done() ticket := 20 own := train.Buy("信阳", ticket) fmt.Printf("李四购票:%d,状态:%t\n", ticket, own) }() go func() { defer wg.Done() ticket := 10 own := train.Buy("信阳", ticket) fmt.Printf("王五购票:%d,状态:%t\n", ticket, own) }() wg.Wait() fmt.Println(train.station) }
运行效果:
TRANSLATE with x English TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back 标签:name,train,季抢票,Add,station,返程,func,go,ticket From: https://www.cnblogs.com/jamstack/p/17678067.html