zoukankan      html  css  js  c++  java
  • 10.5 Synchronizing goroutines with WaitGroup

    Synchronizing goroutines with WaitGroup
    
    While working with concurrently running code branches, it is no exception that at some point the program needs to wait for concurrently running parts of the code. This recipe gives insight into how to use the WaitGroup to wait for running goroutines. 
    
    同步的概念与waitgroup
    在同时运行代码分支时,在某些情况下,程序还需要等待代码的并发运行部分,这也不例外。这个食谱给洞察如何使用waitgroup等待运行的概念。
    
    package main
    
    import "sync"
    import "fmt"
    
    func main() {
    	wg := sync.WaitGroup{}
    	for i := 0; i < 10; i++ {
    		wg.Add(1)
    		go func(idx int) {
    			// Do some work
    			defer wg.Done()
    			fmt.Printf("Exiting %d
    ", idx)
    		}(i)
    	}
    	wg.Wait()
    	fmt.Println("All done.")
    }
    
    /*
    Exiting 9
    Exiting 6
    Exiting 7
    Exiting 8
    Exiting 3
    Exiting 0
    Exiting 1
    Exiting 2
    Exiting 4
    Exiting 5
    All done.
     */
    
    
    
    With help of the  WaitGroup struct from the sync package, the program run is able to wait until some finite number of goroutines finish. The WaitGroup struct implements the method Add to add the number of goroutines to wait for. Then after the goroutine finishes,  the Done method should be called to decrement the number of goroutines to wait for. The method Wait is called as a block until the given number of Done calls has been done (usually at the end of a goroutine). The WaitGroup should be used the same way as all synchronization primitives within the sync package. After the creation of the object, the struct should not be copied.
    
    
    从同步包的waitgroup结构的帮助,程序运行能够等到一些数量有限的概念完成。的waitgroup结构实现方法添加添加Goroutines数等。然后goroutine里完成后,做的方法应该被减数等概念。方法等称为块直到完成调用给定数量已经完成(通常在一个goroutine就结束)。的waitgroup应该用同样的方式为同步包内所有的同步原语。创建对象后,不应复制该结构。
    
    
  • 相关阅读:
    异常练习一 throw
    MAP排序
    Java正则表达式应用详解
    java多线程 sleep()和wait()的区别
    面向对象的15、18位中国大陆身份证号码解析、工具
    java学习笔记--this 关键字的理解
    Java六大问题你都懂了吗?
    Java类的声明和访问介绍
    java的五种数据类型解析
    Java集合框架的总结
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8655074.html
Copyright © 2011-2022 走看看