模拟窗口售票(Go语言实现)

package main

import(
      "fmt"
       "math/rand"
       "runtime"
        "time"
)

var total_ticket  chan int //define a channel to reserve the count of the ticket

func sell(i int){//the params i represents the window number
  for {
         count := <- total_ticket
         if count > 0{
           time.Sleep(time.Duration(rand.Intn(5)))
           total_ticket <- (count -1)
           fmt.Println("id:",i,"ticket:",count)
          }else{
            break
               }
    }

}

func main(){
    runtime.GOMAXPROCS(2)
     total_ticket = make(chan int,5)
    total_ticket <- 100
   rand.Seed(time.Now().Unix())
//create 5 goroutine to sell tickets
   for i:=0;i <5;i++{
       go sell(i)
     }
  //the main function must stop to make the goroutines execute
   time.Sleep(4e9)
  }

  

原文地址:https://www.cnblogs.com/lxy15329/p/2826489.html