Contents

Limit the maximum number of Goroutine and Using channel communication Demo

//statics.lshell.com/home-gopher.png

今天学习了一下 GoLang 协程和及其通信,写了一下 Demo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  
package main  
  
import (  
 "fmt"  
 "strconv"  
 "sync"  
 "time"  
)  
  
// Maximum goroutine  
const goSize = 5  
  
// Producer Producer  
type Producer struct {  
 Item string  
}  
  
// Result result struct  
type Result struct {  
 Code   int  
 Stdout string  
}  
  
// RunJob job  
func RunJob(item string) (result Result) {  
 result.Code = 200  
 result.Stdout = item  
 return  
}  
  
// RoutineRun  go routine run job  
func RoutineRun(wg *sync.WaitGroup, producers chan Producer, result chan Result) {  
 for i := 0; i < goSize; i++ {  
  wg.Add(1)  
  go func() {  
   defer wg.Done()  
   for producer := range producers {  
    time.Sleep(time.Second)  
    ret := RunJob(producer.Item)  
    result <- ret  
   }  
  }()  
 }  
}  
  
func main() {  
 var job Producer  
 wg := &sync.WaitGroup{}  
 jobCount := 20  
 // chan size cannot be smaller than jobCount  
 jobsChan := make(chan Producer, 100)  
 resultChan := make(chan Result, 100)  
  
 for i := 0; i < jobCount; i++ {  
  job.Item = "item: " + strconv.Itoa(i)  
  jobsChan <- job  
 }  
 close(jobsChan)  
  
 RoutineRun(wg, jobsChan, resultChan)  
 wg.Wait()  
 close(resultChan)  
  
 for {  
  ret, ok := <-resultChan  
  if !ok {  
   break  
  }  
  fmt.Println("code: ", ret.Code, "stdout", ret.Stdout)  
 }  
}  
  
  

Github上的高星项目

  1. tunny is a Golang library for spawning and managing a goroutine pool, allowing you to limit work coming from any number of goroutines with a synchronous API.
  2. ants 是一个高性能的 goroutine 池,实现了对大规模 goroutine 的调度管理、goroutine 复用,允许使用者在开发并发程序的时候限制 goroutine 数量,复用资源,达到更高效执行任务的效果。