Go sync.WaitGroup 等待Goroutine执行完成

// A WaitGroup waits for a collection of goroutines to finish.// The main goroutine calls Add to set the number of// goroutines to wait for. Then each of the goroutines// runs and calls Done when finished. At the same time,// Wait can be used to block until all goroutines have finished.//// A WaitGroup must not be copied after first use.type WaitGroup struct {   noCopy noCopy

// 64-bit value: high 32 bits are counter, low 32 bits are waiter count.   // 64-bit atomic operations require 64-bit alignment, but 32-bit   // compilers do not ensure it. So we allocate 12 bytes and then use   // the aligned 8 bytes in them as state.   state1 [12]byte   sema   uint32}

示例代码:

package main

import (
    "sync"
    "fmt"
)

func doWorker(id int, ch chan int, wg *sync.WaitGroup) {
    for n := range ch {
        fmt.Printf("Worker %d received %c\n", id, n)
        wg.Done()    // 减少一个计数
    }
}

type worker struct {
    in chan int
    wg *sync.WaitGroup
}

func createWorker(id int, wg *sync.WaitGroup) worker {
    w := worker{
        in: make(chan int),
        wg: wg,
    }

    go doWorker(id, w.in, wg)
    return w
}

func chanDemo() {
    var wg sync.WaitGroup

    var workers [10]worker

    for i:=0; i<10; i++ {
        workers[i] = createWorker(i, &wg)
    }

    for i, worker := range workers {
        wg.Add(1)      // 添加一个计数
        worker.in <- ‘a‘ + i
    }
    wg.Wait()    // 阻塞,等待所有任务完成

}
func main() {
    chanDemo()
}
// A Mutex is a mutual exclusion lock.// The zero value for a Mutex is an unlocked mutex.//// A Mutex must not be copied after first use.type Mutex struct {   state int32   sema  uint32}

示例代码:

package main

import (
    "sync"
    "fmt"
)

var x = 0

func increment(wg *sync.WaitGroup, mu *sync.Mutex) {
    mu.Lock()
    x++
    mu.Unlock()
    wg.Done()
}

func main() {
    var wg sync.WaitGroup
    var mu sync.Mutex

    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go increment(&wg, &mu)
    }
    wg.Wait()
    fmt.Println("final value of x", x)
}

原文地址:https://www.cnblogs.com/vincenshen/p/9382371.html

时间: 2024-11-11 01:14:08

Go sync.WaitGroup 等待Goroutine执行完成的相关文章

sync.WaitGroup和sync.Once

sync.WaitGroup,顾名思义,等待一组goroutinue运行完毕.sync.WaitGroup声明后即可使用,它有如下方法: func (wg *WaitGroup) Add(delta int) #不能传入符数,否则引发panic func (wg *WaitGroup) Done() func (wg *WaitGroup) Wait() 一般套路是,"先统一Add, 在并发Done, 最后Wait".中心思想是由一个goroutine或主程序来调用Add和Wait方法

Golang的sync.WaitGroup 实现逻辑和源码解析

在Golang中,WaitGroup主要用来做go Routine的等待,当启动多个go程序,通过waitgroup可以等待所有go程序结束后再执行后面的代码逻辑,比如: func Main() { wg := sync.WaitGroup{} for i := 0; i < 10; i++ { wg.Add(1) go func() { defer wg.Done() time.Sleep(10 * time.Second) }() } wg.Wait() // 等待在此,等所有go func

Go并发控制之sync.WaitGroup

WaitGroup 会将main goroutine阻塞直到所有的goroutine运行结束,从而达到并发控制的目的.使用方法非常简单,真心佩服创造Golang的大师们! type WaitGroup               //相当于一个箱子,将main goroutine 保护到里面 func (*WaitGroup) Add   //调用一次为箱子加一把锁(当然,你愿意也可以多把) func (*WaitGroup) Done  // 调用一次开一把锁(only one!) func

golang 的 sync.WaitGroup

WaitGroup的用途:它能够一直等到所有的goroutine执行完成,并且阻塞主线程的执行,直到所有的goroutine执行完成. 官方对它的说明如下: A WaitGroup waits for a collection of goroutines to finish. The main goroutine calls Add to set the number of goroutines to wait for. Then each of the goroutines runs and

golang sync.WaitGroup

//阻塞,直到WaitGroup中的所以过程完成. import ( "fmt" "sync" ) func wgProcess(wg *sync.WaitGroup, id int) { fmt.Printf("process:%d is going!\n", id) //if id == 2 { // return //} wg.Done() } func main() { //var wg sync.WaitGroup wg := new(

linux shell 创建并发后台执行任务并等待任务执行完成

#!/bin/bash echo "i am main" for i in $(seq 1 5) do { sleep 10; echo "i am $i"; }& done wait http://www.cnblogs.com/dorothychai/archive/2012/10/19/2730374.html linux shell 创建并发后台执行任务并等待任务执行完成

C# -- 等待异步操作执行完成的方式

1. 等待异步操作的完成,代码实现 1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Func<int, int> mySum1 = SumNumbers; 6 Func<int, int> mySum2 = SumNumbers; 7 Func<int, int> mySum3 = SumNumbers; 8 9 AsyncCallback callback = c => Console.Wr

C#winform调用外部程序,等待外部程序执行完毕才执行下面代码

1.简单调用外部程序文件(exe文件,批处理等),只需下面一行代码即可 System.Diagnostics.Process.Start(“应用程序文件全路径”); 2.如果要等待调用外部程序执行完毕才执行下面代码,只需要在后面加上WaitForExit()方法 System.Diagnostics.Process.Start(应用程序文件全路径).WaitForExit(); 3.另一种方法:使用实例化方法不使用静态方法 1 Process process = new Process(); 2

Jquery等待ajax执行完毕继续执行(断点调试正常,运行异常)

以前写过一个程序,发现用断点调试的时候,一步步的运行,程序是可以的,但是去了断点程序就出现了问题. $(document).ready(function(){ var arra=new Array(); $.post("/getdata",null,function(data){ for(var i=0;i arra.push(data); } }); $("#item").val(data[0]); }); 发现自己犯了一个错误.首先,看一下$.post与$.aj