[Golang]同步工具-sync包的WaitGroup-心智图总结

1. WaitGroup类型有三个指针方法,Add、Done、Wait
A. 这个类型提供ㄧ个计数器,默认值为0。
B. ㄧ般情况下,会用这个方法来纪录需要等待的goroutine的数量。
C. 通过该类型的Add方法来增加,或者减少计数器的值。
D. Done方法的功能是,对计数器的值进行减ㄧ的操作。
可以在需要等待的goroutine中,通过defer语句调用它
E. Wait方法的功能是,阻塞当前的goroutine,直到其所属值中的计数器归零。
如果Wait方法被调用的时候,计数器的值就是0,它就不会做任何事情。
F. sync.WaitGroup类型计数器的值,不可以小於0

2. 范例程序码

package main

import (
	"fmt"
	"sync"
	"sync/atomic"
	"time"
)

func main() {
  coordinateWithWaitGroup()
}

func coordinateWithWaitGroup() {
  var wg sync.WaitGroup
  wg.Add(2) // 对计数器加2。後面建立两个 goroutine。

  num := int32(0)
  max := int32(10)
  fmt.Printf("The number: %d\n", num)

  // 建立两个 goroutine,对num进行原子操作
  go addNum(&num, 1, max, wg.Done)
  go addNum(&num, 2, max, wg.Done)
  wg.Wait() // 阻塞在这里,等待两个 goroutine 执行结束。
}

// addNum 对numP所指向的变数值,进行原子操作。
func addNum(numP *int32, id, max int32, deferFunc func()) {
  defer func() {
    deferFunc()
  }()
  for i := 0; ; i++ {
    currNum := atomic.LoadInt32(numP)
    if currNum >= max {
      break
    }

    newNum := currNum + 2
    time.Sleep(time.Millisecond * 200)
    if atomic.CompareAndSwapInt32(numP, currNum, newNum) {
      fmt.Printf("The number: %d [%d-%d]\n", currNum, id, i)
    } else {
      fmt.Printf("The CAS operation failed. [%d-%d]\n", id, i)
    }
  }
}

https://play.golang.org/p/qbTXsQJbaon

https://ithelp.ithome.com.tw/upload/images/20201201/20131728EfbESANP4l.png

参考来源:
郝林-Go语言核心36讲
https://github.com/hyper0x/Golang_Puzzlers
https://golang.org/pkg/cmd/go/internal/test/


<<:  Gulp 基础介绍 DAY78

>>:  Windows event 59 sidebyside invalid

06 - Uptime - 掌握系统的生命徵象 (4/4) - 使用合成监控 (Synthetics Monitor) 从使用者情境验证服务的运作状态

Uptime - 掌握系统的生命徵象 系列文章 (1/4) - 我们要观测的生命徵象是什麽? (2/...

第41篇-尝试建立 java 环境并运行 helloworld

尝试运行 java 环境 test@test:~$ sudo apt install openjdk...

[Day29] Whack A Mole Game

[Day29] Whack A Mole Game 打地鼠 需要用到的技巧与练习目标 const s...

switch-case 与select

Golang switch-case 与select 如题来看一下switch-case 与sele...

Day 06 抽离C#程序码

昨天看到FetchData.razor的程序太长了,截图都要两次,为求方便,我们把@code的部分撷...