go sync包(五) WaitGroup
WaitGroup
sync.WaitGroup
可以等待一组 Goroutine 的返回,一个比较常见的使用场景是批量发出 RPC 或者 HTTP 请求:
requests := []*Request{...}
wg := &sync.WaitGroup{}
wg.Add(len(requests))for _, request := range requests {go func(r *Request) {defer wg.Done()// res, err := service.call(r)}(request)
}
wg.Wait()
// In the terminology of the Go memory model, a call to Done
// “synchronizes before” the return of any Wait call that it unblocks.
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 only guarantee that 64-bit fields are 32-bit aligned.// For this reason on 32 bit architectures we need to check in state()// if state1 is aligned or not, and dynamically "swap" the field order if// needed.state1 uint64state2 uint32
}
noCopy
:禁止拷贝。state
:state 是 WaitGroup 的状态数据字段,且是一个无符号64 bit的数据,内容包含了 counter , waiter 信息- counter 代表目前尚未完成的个数,WaitGroup.Add(n) 将会导致 counter += n, 而 WaitGroup.Done() 将导致 counter–。
- waiter 代表目前已调用 WaitGroup.Wait 的 goroutine 的个数。
Add
// Add adds delta, which may be negative, to the WaitGroup counter.
// If the counter becomes zero, all goroutines blocked on Wait are released.
// If the counter goes negative, Add panics.
//
// Note that calls with a positive delta that occur when the counter is zero
// must happen before a Wait. Calls with a negative delta, or calls with a
// positive delta that start when the counter is greater than zero, may happen
// at any time.
// Typically this means the calls to Add should execute before the statement
// creating the goroutine or other event to be waited for.
// If a WaitGroup is reused to wait for several independent sets of events,
// new Add calls must happen after all previous Wait calls have returned.
// See the WaitGroup example.
func (wg *WaitGroup) Add(delta int) {statep, semap := wg.state()if race.Enabled {if delta < 0 {// Synchronize decrements with Wait.race.ReleaseMerge(unsafe.Pointer(wg))}race.Disable()defer race.Enable()}// counter 增加数量state := wg.state.Add(uint64(delta) << 32)// 取出 counterv := int32(state >> 32)// 取出 waiterw := uint32(state)if race.Enabled && delta > 0 && v == int32(delta) {// The first increment must be synchronized with Wait.// Need to model this as a read, because there can be// several concurrent wg.counter transitions from 0.race.Read(unsafe.Pointer(&wg.sema))}// counter < 0,panicif v < 0 {panic("sync: negative WaitGroup counter")}// delta > 0 && v == int32(delta) : 表示从 0 开始添加计数值// w!=0 :表示已经有了等待者// 说明说明在调用了 Wait() 方法之后又想加入新的等待者,这种操作是不允许的if w != 0 && delta > 0 && v == int32(delta) {panic("sync: WaitGroup misuse: Add called concurrently with Wait")}if v > 0 || w == 0 {return}// This goroutine has set counter to 0 when waiters > 0.// Now there can't be concurrent mutations of state:// - Adds must not happen concurrently with Wait,// - Wait does not increment waiters if it sees counter == 0.// Still do a cheap sanity check to detect WaitGroup misuse.// 避免并发调用 Add() 和 Wait()if *statep != state {panic("sync: WaitGroup misuse: Add called concurrently with Wait")}// Reset waiters count to 0.// 唤醒所有 waiter*statep = 0for ; w != 0; w-- {runtime_Semrelease(semap, false, 0)}
}
Wait
// Wait blocks until the WaitGroup counter is zero.
func (wg *WaitGroup) Wait() {statep, semap := wg.state()if race.Enabled {_ = *statep // trigger nil deref early race.Disable()}for {// 读取state// 高32位 ==> counter// 低32位 ==> waiterstate := atomic.LoadUint64(statep)v := int32(state >> 32)w := uint32(state)// counter减到0了,returnif v == 0 {// Counter is 0, no need to wait.if race.Enabled {race.Enable()race.Acquire(unsafe.Pointer(wg))}return}// Increment waiters count.// counter 不为0,waiters++if wg.state.CompareAndSwap(state, state+1) {if race.Enabled && w == 0 {// Wait must be synchronized with the first Add.// Need to model this is as a write to race with the read in Add.// As a consequence, can do the write only for the first waiter,// otherwise concurrent Waits will race with each other.race.Write(unsafe.Pointer(semap))}// 阻塞runtime_Semacquire(semap)// 被唤醒,检查state是否等于0// 不为0,说明存在计数值未恢复为0就重用,panicif *statep != 0 {panic("sync: WaitGroup is reused before previous Wait has returned")}if race.Enabled {race.Enable()race.Acquire(unsafe.Pointer(wg))}return}}
}
Done
// Done decrements the WaitGroup counter by one.
func (wg *WaitGroup) Done() {wg.Add(-1)
}
Done
只是调用了 Add()
,将groutine - 1。
小结
sync.WaitGroup
必须在sync.WaitGroup.Wait
方法返回之后才能被重新使用。sync.WaitGroup.Done
只是对sync.WaitGroup.Add
方法的简单封装,我们可以向sync.WaitGroup.Add
方法传入任意负数(需要保证计数器非负)快速将计数器归零以唤醒等待的 Goroutine。- 可以同时有多个 Goroutine 等待当前 sync.WaitGroup 计数器的归零,这些 Goroutine 会被同时唤醒。
相关文章:

go sync包(五) WaitGroup
WaitGroup sync.WaitGroup 可以等待一组 Goroutine 的返回,一个比较常见的使用场景是批量发出 RPC 或者 HTTP 请求: requests : []*Request{...} wg : &sync.WaitGroup{} wg.Add(len(requests))for _, request : range requests {go func(r *Reque…...
基于深度学习的相机内参标定
基于深度学习的相机内参标定 相机内参标定(Camera Intrinsic Calibration)是计算机视觉中的关键步骤,用于确定相机的内部参数(如焦距、主点位置、畸变系数等)。传统的标定方法依赖于已知尺寸的标定板,通常…...

适合金融行业的国产传输软件应该是怎样的?
对于金融行业来说,正常业务开展离不开文件传输场景,一般来说,金融行业常用的文件传输工具有IM通讯、邮件、自建文件传输系统、FTP应用、U盘等,这些传输工具可以基础实现金融机构的文件传输需求,但也存在如下问题&#…...

昇思25天学习打卡营第9天|MindSpore使用静态图加速(基于context的开启方式)
在Graph模式下,Python代码并不是由Python解释器去执行,而是将代码编译成静态计算图,然后执行静态计算图。 在静态图模式下,MindSpore通过源码转换的方式,将Python的源码转换成中间表达IR(Intermediate Repr…...

class类和style内联样式的绑定
这里的绑定其实就是v-bind的绑定,如代码所示,div后面的引号就是v-bind绑定,然后大括号将整个对象括起来,对象内先是属性,属性后接的是变量,这个变量是定义在script中的,后通过这个变量ÿ…...

3033.力扣每日一题7/5 Java
博客主页:音符犹如代码系列专栏:算法练习关注博主,后期持续更新系列文章如果有错误感谢请大家批评指出,及时修改感谢大家点赞👍收藏⭐评论✍ 目录 思路 解题方法 时间复杂度 空间复杂度 Code 思路 首先创建一个与…...

GPT-5:下一代AI如何彻底改变我们的未来
GPT-5 发布前瞻:技术突破与未来展望 随着科技的飞速发展,人工智能领域不断迎来新的突破。根据最新消息,OpenAI 的首席技术官米拉穆拉蒂在一次采访中确认,GPT-5 将在一年半后发布,并描述了其从 GPT-4 到 GPT-5 的飞跃如…...

重载一元运算符
自增运算符 #include<iostream> using namespace std; class CGirl { public:string name;int ranking;CGirl() { name "zhongge"; ranking 5; }void show() const{ cout << "name : "<<name << " , ranking : " <…...

10元 DIY 一个柔性灯丝氛围灯
之前TikTok上特别火的线性氛围灯Augelight刚出来的时候一度卖到80多美金,国内1688也能到400多人民币。 随着各路国内厂商和DIY创客的跟进,功能变多的同时价格一路下滑,虽然有的质感的确感人,但是便宜啊。 甚至关注的up有把成本搞到…...

表单自定义组件 - 可选择卡片SelectCard
import React from react; import styles from ./index.module.less;type OptionsType {/*** 每个item渲染一行,第0项为标题*/labels?: any[];/*** 自定义渲染内容*/label?: string | React.ReactNode;value: any; }; interface IProps {value?: any;onChange?…...

Ubuntu / Debian安装FTP服务
本章教程,记录在Ubuntu中安装FTP服务的具体步骤。FTP默认端口:21 1、安装 pure-ftpd sudo apt-get install pure-ftpd2、修改默认配置 # 与 centos 不同,这里需要在 /etc/pure-ftpd/conf 文件夹下执行下列命令,增加对应配置文件: # 创建 /etc/pure-ftpd/conf/PureDB 文件…...

若依 Vue 前端分离 3.8.8 版中生成的前端代码中关于下拉框只有下拉箭头的问题
生成代码修改前 <el-form-item label"课程学科" prop"subject"><el-select v-model"queryParams.subject" placeholder"请选择课程学科" clearable><el-optionv-for"dict in course_subject":key"dict…...
C++把一个类封装成动态链接库
一、步骤 1. 创建类头文件 首先,定义你要封装的类。例如,创建一个名为MyClass的类: // MyClass.h #pragma once#ifdef MYCLASS_EXPORTS #define MYCLASS_API __declspec(dllexport) #else #define MYCLASS_API __declspec(dllimport) #end…...
每天一个项目管理概念之项目章程
项目管理中,项目章程扮演着至关重要的角色。它是项目正式启动的标志,为项目的执行提供法律和组织上的认可。项目章程是项目管理知识体系(PMBOK)中定义的关键文档之一,对于确保项目的顺利进行具有决定性的影响。 定义与…...
c++11新特性-4-返回类型后置
文章目录 返回类型后置1.基本语法 返回类型后置 1.基本语法 auto func(参数1,参数2,参数3,...)->decltype(参数表达式) {...... }例如: template<typename T,typename U> auto add(T t,U u)->decltype(t u) {retu…...

Linux-C语言实现一个进度条小项目
如何在linux中用C语言写一个项目来实现进度条?(如下图所示) 我们知道\r是回车,\n是换行(且会刷新) 我们可以用 \r 将光标移回行首,重新打印一样格式的内容,覆盖旧的内容,…...

vue使用glide.js实现轮播图(可直接复制使用)
效果图 可以实现自动轮播,3种切换方式:直接滑动图片、点击两侧按钮、点击底部按钮 体验链接:http://website.livequeen.top 实现 一、引入依赖 1、控制台引入依赖 npm install glidejs/glide 2、在css中引用 <style scoped> import glidejs/g…...

TK养号工具开发会用上的源代码科普!
在当今数字化时代,社交媒体平台的崛起使得网络账号的维护与管理变得日益重要,其中,TK作为一款备受欢迎的社交媒体平台,吸引了大量用户。 在TK上进行账号养护,即通过各种方式提升账号权重、增加曝光量,已成…...

信创-办公软件应用工程师认证
随着国家对信息技术自主创新的战略重视程度不断提升,信创产业迎来前所未有的发展机遇。未来几年内,信创产业将呈现市场规模扩大、技术创新加速、产业链完善和国产化替代加速的趋势。信创人才培养对于推动产业发展具有重要意义。应加强高校教育、建立人才…...
数组操作forEach和map
forEach和map的相同点 1、都是循环遍历数组中的每一项 2、入参匿名函数都支持三个参数,当前项item,当前项索引index,原始数组arr;匿名函数中的this都指向window 3、都可以通过return跳过本次循环 4、都无法通过使用 break 语句来中…...
现有的 Redis 分布式锁库(如 Redisson)提供了哪些便利?
现有的 Redis 分布式锁库(如 Redisson)相比于开发者自己基于 Redis 命令(如 SETNX, EXPIRE, DEL)手动实现分布式锁,提供了巨大的便利性和健壮性。主要体现在以下几个方面: 原子性保证 (Atomicity)ÿ…...

GitFlow 工作模式(详解)
今天再学项目的过程中遇到使用gitflow模式管理代码,因此进行学习并且发布关于gitflow的一些思考 Git与GitFlow模式 我们在写代码的时候通常会进行网上保存,无论是github还是gittee,都是一种基于git去保存代码的形式,这样保存代码…...

搭建DNS域名解析服务器(正向解析资源文件)
正向解析资源文件 1)准备工作 服务端及客户端都关闭安全软件 [rootlocalhost ~]# systemctl stop firewalld [rootlocalhost ~]# setenforce 0 2)服务端安装软件:bind 1.配置yum源 [rootlocalhost ~]# cat /etc/yum.repos.d/base.repo [Base…...

Git 3天2K星标:Datawhale 的 Happy-LLM 项目介绍(附教程)
引言 在人工智能飞速发展的今天,大语言模型(Large Language Models, LLMs)已成为技术领域的焦点。从智能写作到代码生成,LLM 的应用场景不断扩展,深刻改变了我们的工作和生活方式。然而,理解这些模型的内部…...
为什么要创建 Vue 实例
核心原因:Vue 需要一个「控制中心」来驱动整个应用 你可以把 Vue 实例想象成你应用的**「大脑」或「引擎」。它负责协调模板、数据、逻辑和行为,将它们变成一个活的、可交互的应用**。没有这个实例,你的代码只是一堆静态的 HTML、JavaScript 变量和函数,无法「活」起来。 …...

C++--string的模拟实现
一,引言 string的模拟实现是只对string对象中给的主要功能经行模拟实现,其目的是加强对string的底层了解,以便于在以后的学习或者工作中更加熟练的使用string。本文中的代码仅供参考并不唯一。 二,默认成员函数 string主要有三个成员变量,…...

向量几何的二元性:叉乘模长与内积投影的深层联系
在数学与物理的空间世界中,向量运算构成了理解几何结构的基石。叉乘(外积)与点积(内积)作为向量代数的两大支柱,表面上呈现出截然不同的几何意义与代数形式,却在深层次上揭示了向量间相互作用的…...
boost::filesystem::path文件路径使用详解和示例
boost::filesystem::path 是 Boost 库中用于跨平台操作文件路径的类,封装了路径的拼接、分割、提取、判断等常用功能。下面是对它的使用详解,包括常用接口与完整示例。 1. 引入头文件与命名空间 #include <boost/filesystem.hpp> namespace fs b…...

Redis上篇--知识点总结
Redis上篇–解析 本文大部分知识整理自网上,在正文结束后都会附上参考地址。如果想要深入或者详细学习可以通过文末链接跳转学习。 1. 基本介绍 Redis 是一个开源的、高性能的 内存键值数据库,Redis 的键值对中的 key 就是字符串对象,而 val…...

Linux入门(十五)安装java安装tomcat安装dotnet安装mysql
安装java yum install java-17-openjdk-devel查找安装地址 update-alternatives --config java设置环境变量 vi /etc/profile #在文档后面追加 JAVA_HOME"通过查找安装地址命令显示的路径" #注意一定要加$PATH不然路径就只剩下新加的路径了,系统很多命…...