난 당신이 패턴을 따를 것을 제안합니다. 동시성과 채널은 좋지만 나쁜 방식으로 사용하면 프로그램이 예상보다 느려질 수 있습니다. 다중 작업 루틴 및 채널을 처리하는 간단한 방법은 작업자 풀 패턴을 사용하는 것입니다.
이 간단한 예 here에서 가져
// In this example we'll look at how to implement
// a _worker pool_ using goroutines and channels.
package main
import "fmt"
import "time"
// Here's the worker, of which we'll run several
// concurrent instances. These workers will receive
// work on the `jobs` channel and send the corresponding
// results on `results`. We'll sleep a second per job to
// simulate an expensive task.
func worker(id int, jobs <-chan int, results chan<- int) {
for j := range jobs {
fmt.Println("worker", id, "started job", j)
time.Sleep(time.Second)
fmt.Println("worker", id, "finished job", j)
results <- j * 2
}
}
func main() {
// In order to use our pool of workers we need to send
// them work and collect their results. We make 2
// channels for this.
jobs := make(chan int, 100)
results := make(chan int, 100)
// This starts up 3 workers, initially blocked
// because there are no jobs yet.
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
// Here we send 5 `jobs` and then `close` that
// channel to indicate that's all the work we have.
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// Finally we collect all the results of the work.
for a := 1; a <= 5; a++ {
<-results
}
}
아래의 코드를 자세히 살펴 보자. 또한 results
채널은 실패 통지를 포함하여 작업을 실행하는 모든 이동 루틴을 추적하는 데 도움을 줄 수 있습니다.
goroutines가 끝날 때까지 기다리시겠습니까? 그렇다면'sync.WaitGroup'을 사용할 수 있습니다. https://golang.org/pkg/sync/#WaitGroup을 참조하십시오. –
나는이 일을 이해하지 못할 수도있다. 당신은 1000 * 다른 * goroutines을 가지고 있습니까? 그렇지 않은 경우 - 동일한 작업을 수행하면 어떤 항목이 제외 되었습니까? –