openlang

제 go 파이프라인 구현을 검토해주세요 (아직 배우는 중입니다)

여러분 안녕하세요,

go와 동시성 기능을 배우고 있는데, 흔한 패턴 중 하나가 “파이프라인”이더군요. 제가 구현한 버전인데 검토와 개선할 점에 대한 조언을 부탁드립니다

package main

import (
    "context"
    "fmt"
    "runtime"
    "sync"
    "time"
)

func generate(ctx context.Context, inputs chan<- int) {
    defer close(inputs)
    item := 0
    for {
        select {
        case inputs ← item:
            item++
            time.Sleep(60 * time.Millisecond)
        case <-ctx.Done():
            fmt.Println("Ending producer goroutine and inputs channel gracefuly.")
            return
        }
    }
}

func process(inputs <-chan int, outputs chan<- int, group *sync.WaitGroup) {
    defer group.Done()
    for item := range inputs {
        outputs ← item * item
    }
}

func collect(outputs <-chan int) {
    for square := range outputs {
        fmt.Printf("square %d\n", square)
    }
}

func finish(group *sync.WaitGroup, outputs chan<- int) {
    group.Wait()
    close(outputs)
    fmt.Println("Ending coordinator/worker goroutines and outputs channel gracefuly.")
}

func main() {
    ctx, cancel := context.WithTimeout(
        context.Background(),
        1800*time.Millisecond
    )
    defer cancel()

    inputs := make(chan int, 960)
    outputs := make(chan int, 960)

    go generate(ctx, inputs)

    var group sync.WaitGroup
    for range 4 {
        group.Add(1)
        go process(inputs, outputs, &group)
    }

    go finish(&group, outputs)

    collect(outputs)

    fmt.Printf("Pipeline drained completly !\n")
    fmt.Printf("Goroutine count : %d\n", runtime.NumGoroutine()) // expected to be 1
}

그리고 pubsub 같은 중요하고 널리 쓰이는 동시성 패턴 중에서 또 뭘 배워야 할까요.

그럼,

FV

영어에서 번역원문 보기

이어지는 대화 3

서로의 근거를 따라
  1. 고유 링크

    다른 Go 파이프라인 구현과 그 패턴의 바탕이 되는 생각을 살펴보면 어떨까요. 그러면 문제를 더 잘 이해한 뒤 자신의 구현에 어떤 변경이 필요한지 결정할 수 있습니다…

    제 작은 의견입니다…

    영어에서 번역원문 보기
  2. 고유 링크

    여기서 “파이프라인”이 Linux 셸 파이프라인 같은 것을 뜻한다면, 이건 그런 게 아닙니다. 그런 파이프라인의 좋은 점은 동기화 방식을 숨긴다는 겁니다. 그래서 여기에 Sync 코드가 있는 게 의아합니다.

    영어에서 번역원문 보기

같은 질문의 다른 갈래

  1. deep 핸들러에서 함수를 continuation으로 바꾸기

    문서의 deep 핸들러 예제에는 이런 문단이 있어요: 계산 f 자체도 효과를 수행할 수 있습니다. f가 Yield를 수행하면 현재 작업을 멈추고 실행 가능한 작업 큐에 넣은 뒤, 스케줄러가 다음 작업을 실행합니다. 효과가 F…

    답글 3최근 활동 ocaml