Skip to content

Instantly share code, notes, and snippets.

@jdesilvio
Created October 19, 2021 15:11
Show Gist options
  • Save jdesilvio/b6313aa4762e7d002ce28e57e5e8aa06 to your computer and use it in GitHub Desktop.
Save jdesilvio/b6313aa4762e7d002ce28e57e5e8aa06 to your computer and use it in GitHub Desktop.
Go worker pattern
package main
import (
"fmt"
"sync"
"time"
)
func worker(wg *sync.WaitGroup, requestChannel <-chan string, responseChannel chan<- int, id int) {
defer wg.Done()
fmt.Printf("Worker %d starting\n", id)
time.Sleep(time.Second)
for request := range requestChannel {
time.Sleep(time.Second)
fmt.Println(request)
responseChannel <- id * 2
}
}
func monitorWorker(wg *sync.WaitGroup, requestChannel chan string, responseChannel chan int) {
//close(requestChannel)
//wg.Wait()
//close(responseChannel)
}
func printWorker(responseChannel chan int, done chan<- bool) {
time.Sleep(time.Second)
for i := range responseChannel {
fmt.Println(i)
}
//close(responseChannel)
done <- true
}
func main() {
wg := new(sync.WaitGroup)
requestChannel := make(chan string)
responseChannel := make(chan int, 3)
requests := []string{"r1", "r2", "r3"}
for i := 1; i <= 2; i++ {
wg.Add(1)
i := i
go worker(wg, requestChannel, responseChannel, i)
}
for _, request := range requests {
requestChannel <- request
}
//go monitorWorker(wg, requestChannel, responseChannel)
close(requestChannel)
wg.Wait()
close(responseChannel)
fmt.Println("results")
done := make(chan bool, 1)
go printWorker(responseChannel, done)
<-done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment