찾다
백엔드 개발Golangsync.WaitGroup 및 정렬 문제로 이동

이 게시물은 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 



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

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

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

<pre class="brush:php;toolbar:false">func main() {
    var wg sync.WaitGroup

    wg.Add(10)
    for i := 0; i 



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

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

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

for i := 0; i 



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

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

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

<pre class="brush:php;toolbar:false">wg.Add(10)
for i := 0; i 



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

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

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

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

<pre class="brush:php;toolbar:false">for i := 0; i 



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

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

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

<h2>
  
  
  sync.WaitGroup은 어떻게 생겼나요?
</h2>

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

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

<pre class="brush:php;toolbar:false">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으로 문의하세요.
Go Language Pack 가져 오기 : 밑줄과 밑줄이없는 밑줄의 차이점은 무엇입니까?Go Language Pack 가져 오기 : 밑줄과 밑줄이없는 밑줄의 차이점은 무엇입니까?Mar 03, 2025 pm 05:17 PM

이 기사에서는 GO의 패키지 가져 오기 메커니즘을 설명합니다. 명명 된 수입 (예 : 가져 오기 & quot; fmt & quot;) 및 빈 가져 오기 (예 : import _ & quot; fmt & quot;). 명명 된 가져 오기는 패키지 내용을 액세스 할 수있게하고 빈 수입은 t 만 실행합니다.

MySQL 쿼리 결과 목록을 GO 언어로 사용자 정의 구조 슬라이스로 변환하는 방법은 무엇입니까?MySQL 쿼리 결과 목록을 GO 언어로 사용자 정의 구조 슬라이스로 변환하는 방법은 무엇입니까?Mar 03, 2025 pm 05:18 PM

이 기사에서는 MySQL 쿼리 결과를 GO 구조 슬라이스로 효율적으로 변환합니다. 수동 구문 분석을 피하고 최적의 성능을 위해 데이터베이스/SQL의 스캔 방법을 사용하는 것을 강조합니다. DB 태그 및 Robus를 사용한 구조물 필드 매핑에 대한 모범 사례

Beego 프레임 워크에서 페이지간에 단기 정보 전송을 구현하는 방법은 무엇입니까?Beego 프레임 워크에서 페이지간에 단기 정보 전송을 구현하는 방법은 무엇입니까?Mar 03, 2025 pm 05:22 PM

이 기사에서는 웹 애플리케이션에서 페이지 간 데이터 전송에 대한 Beego의 NewFlash () 기능을 설명합니다. NewFlash ()를 사용하여 컨트롤러간에 임시 메시지 (성공, 오류, 경고)를 표시하여 세션 메커니즘을 활용하는 데 중점을 둡니다. 한계

GO에서 제네릭에 대한 사용자 정의 유형 제약 조건을 어떻게 정의 할 수 있습니까?GO에서 제네릭에 대한 사용자 정의 유형 제약 조건을 어떻게 정의 할 수 있습니까?Mar 10, 2025 pm 03:20 PM

이 기사에서는 GO의 제네릭에 대한 사용자 정의 유형 제약 조건을 살펴 봅니다. 인터페이스가 일반 함수에 대한 최소 유형 ​​요구 사항을 정의하여 유형 안전 및 코드 재사성을 향상시키는 방법에 대해 자세히 설명합니다. 이 기사는 또한 한계와 모범 사례에 대해 설명합니다

이동 중에 테스트를 위해 모의 개체와 스터브를 작성하려면 어떻게합니까?이동 중에 테스트를 위해 모의 개체와 스터브를 작성하려면 어떻게합니까?Mar 10, 2025 pm 05:38 PM

이 기사는 단위 테스트를 위해 이동 중에 모의와 스터브를 만드는 것을 보여줍니다. 인터페이스 사용을 강조하고 모의 구현의 예를 제공하며 모의 집중 유지 및 어설 션 라이브러리 사용과 같은 모범 사례에 대해 설명합니다. 기사

편리하게 GO 언어로 파일을 작성하는 방법?편리하게 GO 언어로 파일을 작성하는 방법?Mar 03, 2025 pm 05:15 PM

이 기사는 OS.WriteFile (작은 파일에 적합)과 OS.OpenFile 및 Buffered Writes (큰 파일에 최적)를 비교하여 효율적인 파일 쓰기를 자세히 설명합니다. 강력한 오류 처리, 연기 사용 및 특정 오류 확인을 강조합니다.

GO에서 단위 테스트를 어떻게 작성합니까?GO에서 단위 테스트를 어떻게 작성합니까?Mar 21, 2025 pm 06:34 PM

이 기사는 GO에서 단위 테스트 작성, 모범 사례, 조롱 기술 및 효율적인 테스트 관리를위한 도구를 다루는 것에 대해 논의합니다.

추적 도구를 사용하여 GO 응용 프로그램의 실행 흐름을 이해하려면 어떻게해야합니까?추적 도구를 사용하여 GO 응용 프로그램의 실행 흐름을 이해하려면 어떻게해야합니까?Mar 10, 2025 pm 05:36 PM

이 기사는 추적 도구를 사용하여 GO 응용 프로그램 실행 흐름을 분석합니다. 수동 및 자동 계측 기술, Jaeger, Zipkin 및 OpenTelemetry와 같은 도구 비교 및 ​​효과적인 데이터 시각화를 강조합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.