>  기사  >  백엔드 개발  >  sync.WaitGroup 및 정렬 문제로 이동

sync.WaitGroup 및 정렬 문제로 이동

DDD
DDD원래의
2024-10-22 12:49:29544검색

이 게시물은 Go의 동시성 처리에 관한 시리즈의 일부입니다.

  • 동기화.Mutex: 일반 및 기아 모드
  • sync.WaitGroup 및 정렬 문제로 이동(현재 위치)
  • Sync.Pool과 그 뒤에 숨은 메커니즘
  • 가장 간과되는 동기화 메커니즘, go sync.Cond
  • Go sync.Map: 올바른 작업을 위한 올바른 도구
  • Go Singleflight는 DB가 아닌 코드에 녹아있습니다

WaitGroup은 기본적으로 여러 고루틴이 작업을 마칠 때까지 기다리는 방법입니다.

각 동기화 프리미티브에는 고유한 문제가 있으며 이것도 다르지 않습니다. 우리는 WaitGroup의 정렬 문제에 초점을 맞출 예정이며, 이것이 여러 버전에 걸쳐 내부 구조가 변경된 이유입니다.

이 글은 Go 1.23을 기준으로 작성되었습니다. 앞으로 변경사항이 있으면 X(@func25)를 통해 알려주세요.

sync.WaitGroup이 무엇인가요?

이미 sync.WaitGroup에 익숙하다면 건너뛰셔도 됩니다.

먼저 문제를 살펴보겠습니다. 큰 일을 맡아서 서로 의존하지 않고 동시에 실행할 수 있는 작은 작업으로 나누기로 결정했다고 가정해 보세요.

이를 처리하기 위해 우리는 다음과 같은 작은 작업을 동시에 실행할 수 있는 고루틴을 사용합니다.

func main() {
    for i := 0; i < 10; i++ {
        go func(i int) {
            fmt.Println("Task", i)
        }(i)
    }

    fmt.Println("Done")
}

// Output:
// Done

하지만 다른 고루틴이 작업을 마치기 전에 메인 고루틴이 끝나고 종료될 좋은 기회가 있습니다.

자신의 작업을 수행하기 위해 많은 고루틴을 회전시킬 때, 우리는 주요 고루틴이 다른 모든 사람이 완료되기 전에 끝나거나 종료되지 않도록 이를 추적하고 싶습니다. 이것이 바로 WaitGroup이 등장하는 곳입니다. 고루틴 중 하나가 작업을 마무리할 때마다 WaitGroup에 알립니다.

모든 고루틴이 '완료'로 체크인되면 메인 고루틴은 완료해도 안전하다는 것을 알고 모든 것이 깔끔하게 마무리됩니다.

func main() {
    var wg sync.WaitGroup

    wg.Add(10)
    for i := 0; i < 10; i++ {
        go func(i int) {
            defer wg.Done()
            fmt.Println("Task", i)
        }(i)
    }

    wg.Wait()
    fmt.Println("Done")
}

// Output:
// Task 0
// Task 1
// Task 2
// Task 3
// Task 4
// Task 5
// Task 6
// Task 7
// Task 8
// Task 9
// Done

일반적인 진행 방식은 다음과 같습니다.

  • 고루틴 추가: 고루틴을 시작하기 전에 WaitGroup에 예상되는 수를 알려줍니다. WaitGroup.Add(n)을 사용하여 이 작업을 수행합니다. 여기서 n은 실행하려는 고루틴 수입니다.
  • 고루틴 실행: 각 고루틴은 시작되어 해당 작업을 수행합니다. 완료되면 WaitGroup.Done()을 호출하여 카운터를 1씩 줄여 WaitGroup에 알려야 합니다.
  • 모든 고루틴 대기: 메인 고루틴에서는 무거운 작업을 수행하지 않는 경우 WaitGroup.Wait()를 호출합니다. 그러면 WaitGroup의 카운터가 0에 도달할 때까지 기본 고루틴이 일시 중지됩니다. 간단히 말해서, 다른 모든 고루틴이 완료되고 완료되었음을 알릴 때까지 기다립니다.

일반적으로 고루틴을 실행할 때 WaitGroup.Add(1)이 사용되는 것을 볼 수 있습니다.

for i := 0; i < 10; i++ {   
    wg.Add(1)
    go func() {
        defer wg.Done()
        ...
    }()
}

두 가지 방법 모두 기술적으로는 괜찮지만 wg.Add(1)을 사용하면 성능이 약간 저하됩니다. 그래도 wg.Add(n)를 사용하는 것보다 오류 발생 가능성이 적습니다.

"wg.Add(n)가 오류가 발생하기 쉬운 것으로 간주되는 이유는 무엇입니까?"

핵심은 누군가가 특정 반복을 건너뛰는 continue 문을 추가하는 것처럼 루프의 논리가 나중에 변경되면 상황이 복잡해질 수 있다는 것입니다.

wg.Add(10)
for i := 0; i < 10; i++ {
    if someCondition(i) {
        continue  
    }

    go func() {
        defer wg.Done()
        ...
    }()
}

이 예에서는 루프가 항상 정확히 n개의 고루틴을 시작한다고 가정하고 루프 전에 wg.Add(n)를 사용합니다.

그러나 일부 반복을 건너뛰는 등 해당 가정이 유지되지 않으면 프로그램은 시작되지 않은 고루틴을 기다리다가 멈출 수 있습니다. 그리고 솔직하게 말하자면, 추적하기 정말 힘든 버그입니다.

이 경우에는 wg.Add(1)이 더 적합합니다. 약간의 성능 오버헤드가 발생할 수 있지만 사람의 실수로 인한 오버헤드를 처리하는 것보다 훨씬 낫습니다.

sync.WaitGroup을 사용할 때 사람들이 흔히 저지르는 실수도 있습니다.

for i := 0; i < 10; i++ {
    go func() {
        wg.Add(1)  
        defer wg.Done()
        ...
    }()
}

다음은 wg.Add(1)이 고루틴 내부 호출된다는 점입니다. 기본 고루틴이 이미 wg.Wait()를 호출한 후에 고루틴이 실행되기 시작할 수 있기 때문에 이는 문제가 될 수 있습니다.

이로 인해 온갖 종류의 타이밍 문제가 발생할 수 있습니다. 또한, 위의 모든 예제에서는 wg.Done()을 사용하여 연기합니다. 다중 반환 경로 또는 패닉 복구 문제를 방지하려면 defer와 함께 사용해야 하며 항상 호출되고 호출자를 무기한 차단하지 않도록 해야 합니다.

여기서 모든 기본 사항을 다루어야 합니다.

sync.WaitGroup은 어떻게 생겼나요?

sync.WaitGroup의 소스 코드부터 살펴보겠습니다. sync.Mutex에서도 비슷한 패턴을 발견할 수 있습니다.

다시 한번 말씀드리지만, 뮤텍스 작동 방식에 익숙하지 않으시다면 먼저 Go Sync Mutex: Normal & Starvation Mode 문서를 확인해 보시기 바랍니다.

type WaitGroup struct {
    noCopy noCopy

    state atomic.Uint64 
    sema  uint32
}

type noCopy struct{}

func (*noCopy) Lock()   {}
func (*noCopy) Unlock() {}

Go에서는 구조체를 다른 변수에 할당하기만 하면 쉽게 복사할 수 있습니다. 그러나 WaitGroup과 같은 일부 구조체는 복사하면 안 됩니다.

Copying a WaitGroup can mess things up because the internal state that tracks the goroutines and their synchronization can get out of sync between the copies. If you've read the mutex post, you'll get the idea, imagine what could go wrong if we copied the internal state of a mutex.

The same kind of issues can happen with WaitGroup.

noCopy

The noCopy struct is included in WaitGroup as a way to help prevent copying mistakes, not by throwing errors, but by serving as a warning. It was contributed by Aliaksandr Valialkin, CTO of VictoriaMetrics, and was introduced in change #22015.

The noCopy struct doesn't actually affect how your program runs. Instead, it acts as a marker that tools like go vet can pick up on to detect when a struct has been copied in a way that it shouldn't be.

type noCopy struct{}

func (*noCopy) Lock()   {}
func (*noCopy) Unlock() {}

Its structure is super simple:

  1. It has no fields, so it doesn't take up any meaningful space in memory.
  2. It has two methods, Lock and Unlock, which do nothing (no-op). These methods are there just to work with the -copylocks checker in the go vet tool.

When you run go vet on your code, it checks to see if any structs with a noCopy field, like WaitGroup, have been copied in a way that could cause issues.

It will throw an error to let you know there might be a problem. This gives you a heads-up to fix it before it turns into a bug:

func main() {
    var a sync.WaitGroup
    b := a

    fmt.Println(a, b)
}

// go vet:
// assignment copies lock value to b: sync.WaitGroup contains sync.noCopy
// call of fmt.Println copies lock value: sync.WaitGroup contains sync.noCopy
// call of fmt.Println copies lock value: sync.WaitGroup contains sync.noCopy

In this case, go vet will warn you about 3 different spots where the copying happens. You can try it yourself at: Go Playground.

Note that it's purely a safeguard for when we're writing and testing our code, we can still run it like normal.

Internal State

The state of a WaitGroup is stored in an atomic.Uint64 variable. You might have guessed this if you've read the mutex post, there are several things packed into this single value.

Go sync.WaitGroup and The Alignment Problem

WaitGroup structure

Here's how it breaks down:

  • Counter (high 32 bits): This part keeps track of the number of goroutines the WaitGroup is waiting for. When you call wg.Add() with a positive value, it bumps up this counter, and when you call wg.Done(), it decreases the counter by one.
  • Waiter (low 32 bits): This tracks the number of goroutines currently waiting for that counter (the high 32 bits) to hit zero. Every time you call wg.Wait(), it increases this "waiter" count. Once the counter reaches zero, it releases all the goroutines that were waiting.

Then there's the final field, sema uint32, which is an internal semaphore managed by the Go runtime.

when a goroutine calls wg.Wait() and the counter isn't zero, it increases the waiter count and then blocks by calling runtime_Semacquire(&wg.sema). This function call puts the goroutine to sleep until it gets woken up by a corresponding runtime_Semrelease(&wg.sema) call.

We'll dive deeper into this in another article, but for now, I want to focus on the alignment issues.

Alignment Problem

I know, talking about history might seem dull, especially when you just want to get to the point. But trust me, knowing the past is the best way to understand where we are now.

Let's take a quick look at how WaitGroup has evolved over several Go versions:

Go sync.WaitGroup and The Alignment Problem

sync.WaitGroup in different Go versions

I can tell you, the core of WaitGroup (the counter, waiter, and semaphore) hasn't really changed across different Go versions. However, the way these elements are structured has been modified many times.

When we talk about alignment, we're referring to the need for data types to be stored at specific memory addresses to allow for efficient access.

For example, on a 64-bit system, a 64-bit value like uint64 should ideally be stored at a memory address that's a multiple of 8 bytes. The reason is, the CPU can grab aligned data in one go, but if the data isn't aligned, it might take multiple operations to access it.

Go sync.WaitGroup and The Alignment Problem

Alignment issues

Now, here's where things get tricky:

On 32-bit architectures, the compiler doesn't guarantee that 64-bit values will be aligned on an 8-byte boundary. Instead, they might only be aligned on a 4-byte boundary.

This becomes a problem when we use the atomic package to perform operations on the state variable. The atomic package specifically notes:

"On ARM, 386, and 32-bit MIPS, it is the caller's responsibility to arrange for 64-bit alignment of 64-bit words accessed atomically via the primitive atomic functions." - atomic package note

What this means is that if we don't align the state uint64 variable to an 8-byte boundary on these 32-bit architectures, it could cause the program to crash.

So, what's the fix? Let's take a look at how this has been handled across different versions.

Go 1.5: state1 [12]byte

I'd recommend taking a moment to guess the underlying logic of this solution as you read the code below, then we'll walk through it together.

type WaitGroup struct {
    state1 [12]byte
    sema   uint32
}

func (wg *WaitGroup) state() *uint64 {
    if uintptr(unsafe.Pointer(&wg.state1))%8 == 0 {
        return (*uint64)(unsafe.Pointer(&wg.state1))
    } else {
        return (*uint64)(unsafe.Pointer(&wg.state1[4]))
    }
}

Instead of directly using a uint64 for state, WaitGroup sets aside 12 bytes in an array (state1 [12]byte). This might seem like more than you'd need, but there's a reason behind it.

Go sync.WaitGroup and The Alignment Problem

WaitGroup in Go 1.5

The purpose of using 12 bytes is to ensure there's enough room to find an 8-byte segment that's properly aligned.

The full post is available here: https://victoriametrics.com/blog/go-sync-waitgroup/

위 내용은 sync.WaitGroup 및 정렬 문제로 이동의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.