Go 동시성

Go sync.Mutex

Stop goroutines from losing updates when they change the same value.

  • 고급
  • 4분 분량
  • 실행 가능한 예제 1개
배울 내용
  • Lock and Unlock
  • defer Unlock
  • Why the count is always right
4 goroutines x 1000 increments
  1. 1mu.Lock()one at a time
  2. 2count++safe update
  3. 3mu.Unlock()next goroutine
  4. 44000always

One goroutine at a time

When goroutines change the same variable at the same time, updates can be lost. A Mutex is a lock: only the goroutine that holds it may touch the data.

Lock waits until no other goroutine holds the lock, and defer Unlock releases it when the method returns. Without the mutex, count++ from four goroutines would lose updates. Four goroutines each add 1000, so the result is always 4000.

핵심 포인트

  1. Lock waits until the mutex is free.
  2. defer Unlock releases it on return.
  3. Without a lock, count++ can lose updates.

실행 가능한 Go 예제

Go
코드 실행 →
main.go
package main

import (
	"fmt"
	"sync"
)

type Counter struct {
	mu    sync.Mutex
	count int
}

func (c *Counter) Increment() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.count++
}

func (c *Counter) Value() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.count
}

func main() {
	counter := &Counter{}
	var wg sync.WaitGroup

	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			for j := 0; j < 1000; j++ {
				counter.Increment()
			}
		}()
	}

	wg.Wait()
	fmt.Println("final count:", counter.Value())
}
이 예제의 실행 버튼 만들기 코드 실행 결과
final count: 4000

연습

예제를 온라인 컴파일러에서 열고 값을 바꾸거나 한 줄을 추가한 다음, 실행하기 전에 출력을 예상해 보세요. 그런 다음 일부러 코드를 망가뜨리고 컴파일러 메시지를 읽어 보세요.

이 레슨을 마쳤나요?

학습 완료로 표시하면 진행 상황을 기록할 수 있습니다.

다음: Worker Pool →

챌린지로 연습하기

이 레슨에서 배운 내용으로 실제 문제를 풀어 보세요. 모든 챌린지는 브라우저에서 실행되며 즉시 테스트와 AI 리뷰를 받을 수 있습니다.

모든 챌린지