使用了goroutine實現了多線程,使用chan來控制多線程。
runtime.GOMAXPROCS(3)來設置最大的原生線程。
runtime.Gosched() 顯式地讓出CPU時間給其餘goroutine
代碼以下:redis
1 package main 2 3 import ( 4 "fmt" 5 "runtime" 6 ) 7 8 var quit chan int = make(chan int) 9 10 func print10to19( split_index int) { 11 fmt.Println("Start******print10to19 ") 12 for i := 0; i <= split_index; i++ { 13 // 顯式地讓出CPU時間給其餘goroutine 14 runtime.Gosched() 15 fmt.Println("******10to19: ", i) 16 } 17 fmt.Println("End******print10to19 ") 18 quit <- 1 19 } 20 21 func print20to29(split_index int ) { 22 fmt.Println("Start======print20to29 ") 23 for i := split_index ; i <= 43; i++ { 24 // 顯式地讓出CPU時間給其餘goroutine 25 runtime.Gosched() 26 fmt.Println("======20to29: ", i) 27 } 28 fmt.Println("End======print20to29 ") 29 quit <- 2 30 } 31 32 func print30to39() { 33 fmt.Println("Start######print30to39 ") 34 for i := 30; i < 40; i++ { 35 // 顯式地讓出CPU時間給其餘goroutine 36 runtime.Gosched() 37 fmt.Println("######30to39: ", i) 38 } 39 fmt.Println("End######print30to39 ") 40 quit <- 0 41 } 42 43 func main() { 44 // 設置最大開n個原生線程 45 runtime.GOMAXPROCS(3) 46 47 fmt.Println("start ---") 48 49 split_index := split_token() 50 51 go print10to19(split_index) 52 go print20to29(split_index + 1) 53 // go print30to39() 54 55 // go print10to19(begin1,end1) 56 // go print20to29(begin2,end2) 57 fmt.Println("start ===") 58 for i := 0; i < 2; i++ { 59 sc := <-quit 60 fmt.Println("sc:", sc) 61 } 62 63 fmt.Println("end") 64 } 65 66 67 // 拆分設備組 68 func split_token() int{ 69 70 // redisMaster := midware.NewPRedis(config.Config.GetString("REDIS_MASTER")) 71 // group_len, err := redisMaster.ZCard(str.GID) // 獲取redis組的設備總數 72 73 // 測試:拆分紅2個協程 74 // split_task(2,0,group_len) 75 res := split_task(2,0,43) 76 return res 77 } 78 79 80 func split_task(N int, WholeBegin int, WholeEnd int) int{ 81 82 res := (WholeEnd - WholeBegin) / N 83 84 switch res { 85 case 0: 86 fmt.Printf("0....%s",WholeEnd) 87 default: 88 fmt.Printf("Default012", res) 89 } 90 91 return res 92 }
運行程序:多線程
能夠看出,進程1跑的是0——21,進程2跑的是22——43,ide
這裏拆分紅2個進程。可根據本身的需求,拆分紅多個進程處理。多個進程同時跑拆分一個大的group組的數據。測試
這種場景是:一個很大的數據表,若M個億的數據,要是開啓單進程執行的話,可能須要時間T;ui
但要是開啓多N個進程,拆分這個M個億的數據,至關於每一個進程同時在處理M/N 的數據,分而治之的處理一個很大的數據量。spa