Heim  >  Artikel  >  Backend-Entwicklung  >  Gehen Sie zu sync.WaitGroup und dem Ausrichtungsproblem

Gehen Sie zu sync.WaitGroup und dem Ausrichtungsproblem

DDD
DDDOriginal
2024-10-22 12:49:29544Durchsuche

Dieser Beitrag ist Teil einer Serie über den Umgang mit Parallelität in Go:

  • Go sync.Mutex: Normal- und Hungermodus
  • Gehen Sie zu sync.WaitGroup und The Alignment Problem (Wir sind hier)
  • Go sync.Pool und die Mechanismen dahinter
  • Gehen Sie zu sync.Cond, dem am meisten übersehenen Synchronisierungsmechanismus
  • Go sync.Map: Das richtige Tool für den richtigen Job
  • Go Singleflight schmilzt in Ihrem Code, nicht in Ihrer Datenbank

WaitGroup ist im Grunde eine Möglichkeit, darauf zu warten, dass mehrere Goroutinen ihre Arbeit beenden.

Jedes der Synchronisierungsprimitive hat seine eigenen Probleme, und dieses hier ist nicht anders. Wir werden uns auf die Ausrichtungsprobleme mit WaitGroup konzentrieren, weshalb sich die interne Struktur in den verschiedenen Versionen geändert hat.

Dieser Artikel basiert auf Go 1.23. Wenn sich später etwas ändert, lassen Sie es mich gerne über X(@func25) wissen.

Was ist sync.WaitGroup?

Wenn Sie bereits mit sync.WaitGroup vertraut sind, können Sie gerne weitermachen.

Lassen Sie uns zunächst auf das Problem eingehen. Stellen Sie sich vor, Sie haben eine große Aufgabe zu erledigen und beschließen, diese in kleinere Aufgaben aufzuteilen, die gleichzeitig ausgeführt werden können, ohne voneinander abhängig zu sein.

Um dies zu bewältigen, verwenden wir Goroutinen, da sie diese kleineren Aufgaben gleichzeitig ausführen lassen:

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

    fmt.Println("Done")
}

// Output:
// Done

Aber hier ist die Sache, es besteht eine gute Chance, dass die Haupt-Goroutine fertig ist und beendet wird, bevor die anderen Goroutinen mit ihrer Arbeit fertig sind.

Wenn wir viele Goroutinen ausgliedern, um ihr Ding zu erledigen, wollen wir den Überblick über sie behalten, damit die Haupt-Goroutine nicht einfach fertig wird und beendet wird, bevor alle anderen fertig sind. Hier kommt die WaitGroup ins Spiel. Jedes Mal, wenn eine unserer Goroutinen ihre Aufgabe abschließt, teilt sie dies der WaitGroup mit.

Sobald alle Goroutinen als „erledigt“ eingecheckt haben, weiß die Haupt-Goroutine, dass sie sicher fertig werden kann, und alles wird ordentlich abgeschlossen.

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

So läuft es normalerweise ab:

  • Goroutinen hinzufügen: Bevor Sie mit Ihren Goroutinen beginnen, teilen Sie der WaitGroup mit, mit wie vielen Sie rechnen müssen. Sie tun dies mit WaitGroup.Add(n), wobei n die Anzahl der Goroutinen ist, die Sie ausführen möchten.
  • Goroutinen laufen: Jede Goroutine geht los und macht ihre Sache. Wenn es fertig ist, sollte es die WaitGroup darüber informieren, indem es WaitGroup.Done() aufruft, um den Zähler um eins zu reduzieren.
  • Warten auf alle Goroutinen: In der Hauptgoroutine, die nicht die schwere Arbeit erledigt, rufen Sie WaitGroup.Wait() auf. Dadurch wird die Haupt-Goroutine angehalten, bis der Zähler in der WaitGroup Null erreicht. Im Klartext: Es wartet, bis alle anderen Goroutinen fertig sind und signalisieren, dass sie fertig sind.

Normalerweise wird WaitGroup.Add(1) beim Starten einer Goroutine verwendet:

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

Beide Möglichkeiten sind technisch in Ordnung, aber die Verwendung von wg.Add(1) hat einen kleinen Leistungseinbruch. Dennoch ist es weniger fehleranfällig als die Verwendung von wg.Add(n).

"Warum wird wg.Add(n) als fehleranfällig angesehen?"

Der Punkt ist, dass die Dinge chaotisch werden können, wenn sich die Logik der Schleife im Laufe der Zeit ändert, beispielsweise wenn jemand eine Continue-Anweisung hinzufügt, die bestimmte Iterationen überspringt:

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

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

In diesem Beispiel verwenden wir wg.Add(n) vor der Schleife, vorausgesetzt, die Schleife startet immer genau n Goroutinen.

Aber wenn diese Annahme nicht zutrifft, beispielsweise wenn einige Iterationen übersprungen werden, bleibt Ihr Programm möglicherweise hängen und wartet auf Goroutinen, die nie gestartet wurden. Und seien wir ehrlich, das ist die Art von Fehler, deren Aufspüren sehr mühsam sein kann.

In diesem Fall ist wg.Add(1) besser geeignet. Es ist vielleicht mit einem kleinen Leistungsaufwand verbunden, aber es ist viel besser, als mit dem menschlichen Fehler umzugehen.

Es gibt auch einen ziemlich häufigen Fehler, den Leute machen, wenn sie sync.WaitGroup verwenden:

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

Das kommt darauf an, dass wg.Add(1) innerhalb der Goroutine aufgerufen wird. Dies kann ein Problem darstellen, da die Goroutine möglicherweise mit der Ausführung beginnt, nachdem die Haupt-Goroutine bereits wg.Wait() aufgerufen hat.

Das kann zu allen möglichen Timing-Problemen führen. Wie Sie außerdem bemerken, verwenden alle oben genannten Beispiele defer mit wg.Done(). Es sollte in der Tat mit „Defer“ verwendet werden, um Probleme mit mehreren Rückpfaden oder Panic-Recovery zu vermeiden und sicherzustellen, dass es immer aufgerufen wird und den Anrufer nicht auf unbestimmte Zeit blockiert.

Das sollte alle Grundlagen abdecken.

Wie sieht sync.WaitGroup aus?

Beginnen wir damit, uns den Quellcode von sync.WaitGroup anzusehen. Sie werden ein ähnliches Muster in sync.Mutex bemerken.

Auch wenn Sie nicht mit der Funktionsweise eines Mutex vertraut sind, empfehle ich Ihnen dringend, zuerst diesen Artikel zu lesen: 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() {}

In Go ist es einfach, eine Struktur zu kopieren, indem Sie sie einfach einer anderen Variablen zuweisen. Aber einige Strukturen, wie etwa WaitGroup, sollten wirklich nicht kopiert werden.

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/

Das obige ist der detaillierte Inhalt vonGehen Sie zu sync.WaitGroup und dem Ausrichtungsproblem. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn