我是golang的绿色代表,当我学习golang时,我对下面的练习代码感到困惑
package main
import (
"fmt"
"math/rand"
"runtime"
"time"
)
var ticket = 10
func saleTickets(name string) {
rand.Seed(time.Now().UnixNano())
for {
if ticket > 0 {
fmt.Println(name, "sold:", ticket)
ticket--
} else {
fmt.Println(name, "no tickets")
break
}
}
}
func main() {
runtime.GOMAXPROCS(1)
go saleTickets("TicketWindow1")
go saleTickets("TicketWindow2")
go saleTickets("TicketWindow3")
go saleTickets("TicketWindow4")
time.Sleep(2 * time.Second)
}
这是结果:
TicketWindow1 sold: 10
9
TicketWindow1 sold: 9
8
TicketWindow1 sold: 8
7
TicketWindow1 sold: 7
6
TicketWindow1 sold: 6
5
TicketWindow1 sold: 5
4
TicketWindow1 sold: 4
3
TicketWindow1 sold: 3
2
TicketWindow1 sold: 2
1
TicketWindow1 sold: 1
0
TicketWindow1 no tickets
TicketWindow4 sold: 10
-1
TicketWindow4 no tickets
TicketWindow2 sold: 10
-2
TicketWindow2 no tickets
TicketWindow3 sold: 10
-3
TicketWindow3 no tickets
我不知道为什么会这样。...票证是一个全局变量,在第一个goroutine完成后票证应该为0,但是其他goroutine仍然是10,实际上没有10