Golang gorouting 并发控制 sync.WaitGroup 介绍与使用

WaitGroup简称同步组,用于等待goroutines结束的。

官方文档:

type WaitGroup

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.

翻译过来就是:WaitGroup用来等待goroutings退出,主进程调用Add设置等待的协程数量,在协程里面结束的时候调用Done方法。Wait方法将会阻塞直到所有协程都调用Done方法退出。

WaitGroup不能被复制使用,可以以指针的方式传递。

func (wg *WaitGroup) Add(delta int)
增加wg计数器

func (wg *WaitGroup) Done()
wg计数器减一

func (wg *WaitGroup) Wait()
等待直到wg计数器变为0

用例:

// wg.go
package main

import (
	"fmt"
	"sync"
)

func child(wg *sync.WaitGroup, i int) {
	fmt.Printf("child:%d, exit \n", i)
	wg.Done()
}

func main() {

	//定义一个WaitGroup变量
	var wg sync.WaitGroup

	//添加gorouting
	for i := 0; i <= 5; i++ {
		wg.Add(1)
		go child(&wg, i)
	}

	//等待gorouting退出
	wg.Wait()
	fmt.Printf("all gorouting exit\n")
	return
}

运行结果:

参考文档:

1. https://golang.org/pkg/sync/#WaitGroup

Go语言中的channel、sync.WaitGroup和context是三个非常重要的并发编程工具。下面我将对它们进行详细介绍。 ### Channel Go语言中的channel是一种在多个goroutine之间进行通信的机制。也可以说,channel是一种数据结构,它可以让一个goroutine向另一个goroutine发送一个值,同时还可以让另一个goroutine从channel中接收这个值。在Go语言中,使用make函数创建一个channel。例如: ```go ch := make(chan int) ``` 这行代码创建了一个类型为int的channel。可以在goroutine中使用ch <- value语句向channel发送一个整数,例如: ```go go func() { ch <- 1 }() ``` 可以使用value := <- ch语句从channel中接收一个整数,例如: ```go value := <- ch ``` 这行代码会阻塞,直到有一个整数被发送到这个channel中为止。需要注意的是,如果没有接收者,发送操作会一直阻塞,直到有接收者为止;如果没有发送者,接收操作也会一直阻塞,直到有发送者为止。 ### sync.WaitGroup sync.WaitGroup是Go语言中的一个同步工具,它可以等待一组goroutine完成工作。在WaitGroup中,每个goroutine的工作完成后,都需要调用Done方法。主goroutine可以在Wait方法上阻塞,等待所有的goroutine完成工作。例如: ```go var wg sync.WaitGroup for i := 0; i < 10; i++ { wg.Add(1) go func() { // do some work wg.Done() }() } wg.Wait() ``` 这行代码创建了一个WaitGroup,并且启动了10个goroutine进行工作。每个goroutine完成工作后,都会调用wg.Done方法,主goroutine在wg.Wait上阻塞,等待所有的goroutine完成工作。 ### context context是Go语言中的一个用于传递请求范围数据的机制。在一个请求处理中,可以使用context携带一些请求数据,同时也可以使用context取消请求处理。例如: ```go func handleRequest(ctx context.Context) { // do some work select { case <-ctx.Done(): // handle cancelation default: // continue working } } ``` 这行代码定义了一个处理请求的函数,该函数接收一个context参数。如果context被取消,处理请求的函数将会停止工作。例如: ```go ctx, cancel := context.WithCancel(context.Background()) go func() { time.Sleep(time.Second) cancel() }() handleRequest(ctx) ``` 这行代码创建了一个带有取消功能的context,并且启动了一个goroutine在1秒后取消context。handleRequest函数会使用这个context来处理请求,并且如果context被取消,handleRequest函数会立刻停止工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值