Skip to content

Instantly share code, notes, and snippets.

@leosunmo
Last active June 10, 2020 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leosunmo/b0ad5433fd7580578090cf512284a11a to your computer and use it in GitHub Desktop.
Save leosunmo/b0ad5433fd7580578090cf512284a11a to your computer and use it in GitHub Desktop.
Golang workers/channels example
package main
import (
"fmt"
"math/rand"
"os"
"os/signal"
"time"
)
type worker struct {
num int
quit chan struct{}
work chan int
}
func main() {
workCh := make(chan int, 20)
quitCh := make(chan struct{}, 5)
resultCh := make(chan string)
for i := 0; i < 5; i++ {
w := worker{
num: i,
work: workCh,
quit: quitCh,
}
go w.process(resultCh)
}
go func() {
for results := range resultCh {
fmt.Println(results)
}
}()
for j := 0; j < 20; j++ {
max := 4000
min := 100
workCh <- rand.Intn(max-min) + min
}
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
// Received first interrupt, perform graceful shutdown
fmt.Println("Gracefully shutting down")
// do nice graceful shutdown...
for i := 0; i < 5; i++ {
quitCh <- struct{}{}
}
<-c
// Received second interrupt, quit
fmt.Println("Received kill, quiting now")
close(resultCh)
}
func (w worker) process(result chan<- string) {
fmt.Printf("[%d] Starting worker\n", w.num)
for {
select {
case dur := <-w.work:
// Doing some work
time.Sleep(time.Duration(dur) * time.Millisecond)
result <- fmt.Sprintf("[%d] Finished my work", w.num)
case <-w.quit:
fmt.Printf("[%d] shutting down worker\n", w.num)
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment