生產者與消費者
阿新 • • 發佈:2017-11-13
bsp ++ 生產 ons sin range taxi max continue
1 package main 2 3 import ( 4 "fmt" 5 "gitee.com/ha666/golibs" 6 "github.com/astaxie/beego/logs" 7 _ "ha666/initial" 8 "math" 9 "time" 10 ) 11 12 func main() { 13 ch := make(chan int, 100000) 14 defer close(ch) 15 for i := 1; i < 3; i++ { 16 go producer(fmt.Sprintf("生產者%d", i), i, ch) 17 } 18 19 time.Sleep(1 * time.Second) 20 21 for i := 1; i < 5; i++ { 22 go consumer(fmt.Sprintf("消費者%d", i), i, ch) 23 } 24 time.Sleep(math.MaxInt64) 25 } 26 27 func producer(pname string, t_id int, ch chan int) { 28 for i := 1; ; i++ {29 if len(ch) > 300 { 30 fmt.Println(golibs.StandardTime(), "暫停生產10秒") 31 time.Sleep(time.Second * 10) 32 continue 33 } 34 time.Sleep(time.Duration(3) * time.Millisecond) 35 fmt.Println(golibs.StandardTime(), pname, " : ", i) 36ch <- i 37 lch := len(ch) 38 if lch >= 300 { 39 logs.Info("【生產】隊列中已經有%d個,暫停10秒", lch) 40 time.Sleep(time.Second * 10) 41 } 42 } 43 } 44 45 func consumer(uname string, t_id int, ch chan int) { 46 count := 0 47 t1 := time.Now() 48 b := 0 49 for i := range ch { 50 b, i = i, b 51 time.Sleep(time.Duration(t_id) * time.Millisecond) 52 count++ 53 if count >= 1000 { 54 t2 := golibs.Since(t1) 55 logs.Info("【消費】%s共執行%d項,耗時:%d毫秒", uname, count, t2) 56 count = 0 57 t1 = time.Now() 58 } 59 } 60 }
生產者與消費者