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

[Go Learning] Concurrency Control WaitGroup Counting Semaphore

little bottle
Release: 2023-04-06 07:00:02
forward
3488 people have browsed it

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结束")
}
Copy after login

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!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template