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应该用同样的方式为同步包内所有的同步原语。创建对象后,不应复制该结构。
    
    
  • 相关阅读:
    学习web前端要去一线就业吗
    程序员什么时候该考虑跳槽
    前端工程师应该具备怎样的一种技术水平
    如何掌握学习移动端Web页面布局
    如何优化Web前端技术开发生态体系
    想进名企大厂?阿里程序员给你三点建议
    对即将入职前端工作的新人有哪些建议?
    Java基础学习之快速掌握Session和cookie
    Java入门学习之JDK介绍与初次编程实现
    Java编译的运行机制初步讲解
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8655074.html
Copyright © 2011-2022 走看看