这是一个buyTicket程序,当ticket为0时,会显示“sell out”。我想知道为什么我不能在 buyTicket 函数中添加 sleep 以及为什么票会是负数?
func(t *Ticket) buyTicket() {
if t.getSpareTicket() <= 0 {
log.Print("sell out")
return
}
t.mu.Lock()
t.numTicket--
time.Sleep(time.Microsecond)
log.Printf("there are %d", t.numTicket)
t.mu.Unlock()
}
func (t *Ticket) getSpareTicket() int{
t.mu.Lock()
defer t.mu.Unlock()
return t.numTicket
}
func main() {
buyer := &Ticket{}
buyer.mu = sync.Mutex{}
buyer.numTicket = 100
for buyer.getSpareTicket() > 0 {
//time.Sleep(time.Microsecond)
go func() {
log.Printf("number buy a ticket")
buyer.buyTicket()
}()
}
time.Sleep(time.Second * 2)
//l := buyer.getSpareTicket()
//fmt.Println(l)
}
当我在函数 buyTicket 中添加 time.sleep(time.microsecond) 时,ticket 将为负数,我想知道为什么会这样?
这是结果:
2020/11/15 15:36:00 there are 2
2020/11/15 15:36:00 there are 1
2020/11/15 15:36:00 there are 0
2020/11/15 15:36:00 there are -1
2020/11/15 15:36:00 there are -2
2020/11/15 15:36:00 there are -3
2020/11/15 15:36:00 there are -4
2020/11/15 15:36:00 there are -5
大话西游666
相关分类