WaitGroup并发控制原理及底层源码实现

1.1实现原理

1.2底层源码

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 uint64
state2 uint32
}
func (wg *WaitGroup) Add(delta int) {
statep, semap := wg.state()
if race.Enabled {
_ = *statep // trigger nil deref early
if delta < 0 {
// Synchronize decrements with Wait.
race.ReleaseMerge(unsafe.Pointer(wg))
}
race.Disable()
defer race.Enable()
}
//把delta左移32位累加到state,即累加到counter中
state := atomic.AddUint64(statep, uint64(delta)<<32)
v := int32(state >>

本文详细阐述了Go语言中的WaitGroup并发控制机制,包括实现原理,底层源码分析,并重点讲解了CAS(CompareAndSwap)在WaitGroup中的应用,以及两个示例展示了CAS操作的工作流程。
最低0.47元/天 解锁文章
254

被折叠的 条评论
为什么被折叠?



