Last active
June 10, 2020 00:28
-
-
Save leosunmo/b0ad5433fd7580578090cf512284a11a to your computer and use it in GitHub Desktop.
Revisions
-
leosunmo revised this gist
Jun 10, 2020 . 1 changed file with 5 additions and 3 deletions.There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -16,7 +16,7 @@ type worker struct { func main() { workCh := make(chan int, 20) quitCh := make(chan struct{}, 5) resultCh := make(chan string) for i := 0; i < 5; i++ { w := worker{ @@ -45,10 +45,12 @@ func main() { // 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) } @@ -61,7 +63,7 @@ func (w worker) process(result chan<- string) { 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 } } -
leosunmo created this gist
Jun 10, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,68 @@ 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{}) 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... <-c // Received second interrupt, quit fmt.Println("Received kill, quiting now") quitCh <- struct{}{} 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", w.num) return } } }