Przykład basenu Golang Goroutine
package main
import (
"fmt"
"sync"
)
var wg sync.WaitGroup
func worker(input chan string, output chan string) {
defer wg.Done()
// Consumer: Process items from the input channel and send results to output channel
for value := range input {
output <- value + " processed"
}
}
func main() {
var jobs = []string{"one", "two", "three", "four", "two", "three", "four", "two", "three", "four", "two", "three", "four", "two", "three", "four", "two"}
input := make(chan string, len(jobs))
output := make(chan string, len(jobs))
workers := 250
// Increment waitgroup counter and create go routines
for i := 0; i < workers; i++ {
wg.Add(1)
go worker(input, output)
}
// Producer: load up input channel with jobs
for _, job := range jobs {
input <- job
}
// Close input channel since no more jobs are being sent to input channel
close(input)
// Wait for all goroutines to finish processing
wg.Wait()
// Close output channel since all workers have finished processing
close(output)
// Read from output channel
for result := range output {
fmt.Println(result)
}
}
Restu Wahyu Saputra