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应该用同样的方式为同步包内所有的同步原语。创建对象后,不应复制该结构。
    
    
  • 相关阅读:
    世界十大黑客简介
    Workerman
    获取当前页面完整路径的方法:
    冒泡排序
    伪静态规则
    PHP如何打印出curl 模块交互的 http 请求与响应 header?
    转 浅谈 PHP 与手机 APP 开发(API 接口开发)
    银联chinapay支付接口实现详解
    PHP webservice 接口实例
    spl_autoload_register方法
  • 原文地址:https://www.cnblogs.com/zrdpy/p/8655074.html
Copyright © 2011-2022 走看看