PHpullh
학습 라이브러리/Go/세마포어 패턴

GO · 고루틴/채널

세마포어 패턴

버퍼 채널로 세마포어를 구현하여 동시 실행 수를 제한합니다.

고루틴/채널중급semaphoreconcurrencylimitchannel

핵심 설명

버퍼 채널로 세마포어를 구현하여 동시 실행 수를 제한합니다.

Go code

package main

import (
	"fmt"
	"sync"
	"time"
)

type Semaphore struct {
	ch chan struct{}
}

func NewSemaphore(max int) *Semaphore {
	return &Semaphore{ch: make(chan struct{}, max)}
}

func (s *Semaphore) Acquire() { s.ch <- struct{}{} }
func (s *Semaphore) Release() { <-s.ch }

func main() {
	sem := NewSemaphore(3) // 최대 3개 동시 실행
	var wg sync.WaitGroup

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func(id int) {
			defer wg.Done()
			sem.Acquire()
			defer sem.Release()

			fmt.Printf("[%s] 작업 %d 시작\n",
				time.Now().Format("05.000"), id)
			time.Sleep(500 * time.Millisecond)
		}(i)
	}

	wg.Wait()
	fmt.Println("모든 작업 완료")
}

학습 팁

세마포어는 데이터베이스 커넥션, API 호출 등 외부 리소스 접근 제한에 효과적입니다.

주의할 점

AcquireRelease 횟수가 일치하지 않으면 교착 상태가 발생합니다. defer Release()를 습관화하세요.

자주 묻는 질문

세마포어 패턴란 무엇인가요?

버퍼 채널로 세마포어를 구현하여 동시 실행 수를 제한합니다.

세마포어 패턴 학습 시 주의할 점은 무엇인가요?

Acquire 와 Release 횟수가 일치하지 않으면 교착 상태가 발생합니다. defer Release() 를 습관화하세요.

Continue Learning

Go 학습을 이어가세요

총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.