Home  >  Article  >  Backend Development  >  [Go Learning] Concurrency Control WaitGroup Counting Semaphore

[Go Learning] Concurrency Control WaitGroup Counting Semaphore

little bottle
little bottleforward
2019-04-20 09:26:233402browse

The editor of this article will take you to learn the WaitGroup counting semaphore in concurrency control in the go language, and attach the use case code, which has certain reference value. Interested friends come and learn it!

WaitGroup is a counting semaphore that can be used to record and maintain running goroutine. If the value of WaitGroup is greater than 0, the Wait method will block

Call the Done method to reduce the value of WaitGroup. And finally release the main function


package main
import(
        "fmt"
        "runtime"
        "sync"
)
func main(){
        //只分配一个逻辑处理器给调度器使用
        runtime.GOMAXPROCS(1)
        //wg用来使main goroutine等待子goroutine结束
        var wg sync.WaitGroup
        //等待两个子goroutine结束
        wg.Add(2)
        fmt.Println("开启goroutine")
        go func(){
                defer wg.Done()
                //循环显示三遍字母表
                for count:=0;count<3;count++{
                        //循环显示字母表
                        for char:=&#39;a&#39;;char<&#39;a&#39;+26;char++{
                                fmt.Printf("%c ",char)
                        }   
                }   
        }() 
        go func(){
                defer wg.Done()
                //循环显示三遍字母表
                for count:=0;count<3;count++{
                        //循环显示字母表
                        for char:=&#39;A&#39;;char<&#39;A&#39;+26;char++{
                                fmt.Printf("%c ",char)
                        }   
                }   
        }() 
        //main goroutine等待子goroutine结束
        wg.Wait()
        fmt.Println("\ngoroutine结束")
}

If you want to know more go language tutorials, go and follow the go video tutorial on the PHP Chinese website!

The above is the detailed content of [Go Learning] Concurrency Control WaitGroup Counting Semaphore. For more information, please follow other related articles on the PHP Chinese website!

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