Home  >  Article  >  Backend Development  >  Methods to control the number of concurrency in go language

Methods to control the number of concurrency in go language

尚
forward
2020-06-17 17:48:473328browse

Methods to control the number of concurrency in go language

Because the Go language supports concurrency, concurrency questions are often asked in interviews. For example, what are the ways to control the number of go concurrencies? The following are two examples that I personally compiled:

func waitGroup() {
    count := 10
    wg := sync.WaitGroup{}

    for i := 0; i < count; i++ {
        wg.Add(1)
        go func(j int) {
            fmt.Print(j)
            wg.Done() // 也可使用 wg.Add(-1)
        }(i)
    }

    wg.Wait()
}

The above mainly uses the waitGroup under the sync package in go. This is also a common implementation method at work. The key point is to grasp the Add method. Position, the Wait method is to wait for all coroutines to be executed

func channel() {
    count := 10 // 最大支持并发
    sum := 100 // 任务总数

    c := make(chan struct{}, count) // 控制任务并发的chan
    sc := make(chan struct{}, sum) // 控制任务总数的chan
    defer close(c)
    defer close(sc)

    for i:=0; i<sum;i++{
        c <- struct{}{} // 作用类似于waitgroup.Add(1)
        go func(j int) {
            fmt.Println(j)
            <- c // 执行完毕,释放资源
            sc <- struct {}{} // 记录到执行总数里
        }(i)
    }

    for i:=sum; i>0;i-- {
        <- sc
    }
}

The above example uses the channel in go, using the channel blocking feature and the buffered channel to control the number of concurrencies, where sc This channel can be removed. In the example, it is only used to prevent all output from not being output after the main program exits. In normal operation, the program is generally blocking, so it can be removed.

For more related knowledge, please pay attention to the go language tutorial column

The above is the detailed content of Methods to control the number of concurrency in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete