Created
January 29, 2018 20:40
-
-
Save Yuffster/976ab030162f02fb66cefae1e747e54c to your computer and use it in GitHub Desktop.
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 characters
package main | |
import "fmt" | |
import "time" | |
import "syscall" | |
import "os" | |
import "os/signal" | |
type fn func(os.Signal) | |
func catchSigterm(fun fn) { | |
c := make(chan os.Signal, 1) | |
signal.Notify(c, os.Interrupt, syscall.SIGTERM) | |
go func() { | |
s := <- c // we get signal | |
fun(s) | |
}() | |
} | |
func main() { | |
sigterm := false | |
catchSigterm(func (sig os.Signal) { | |
fmt.Println("\nCaught sigterm...\n") | |
sigterm = true | |
}); | |
c := make(chan string) | |
words := []string{"hello", "world", "here", "are", "a", "bunch", "of", "words"} | |
i := 0 | |
pending := 0 | |
for j:=0;j<4;j++ { | |
go sleepThenSay(words[0], i, c) | |
pending += 1 | |
} | |
for { | |
w := <- c | |
fmt.Println(w) | |
fmt.Printf("[%d] Waiting...\n", pending) | |
w = <- c | |
pending -= 1 | |
fmt.Println(w) | |
i += 1 | |
if (i >= len(words)) { | |
i = 0 | |
} | |
if sigterm { | |
if pending == 0 { | |
fmt.Printf("Done waiting...!") | |
os.Exit(0) | |
} | |
fmt.Printf("\nSkipping next call, waiting for %d threads to finish...", pending) | |
} else { | |
pending += 1 | |
go sleepThenSay(words[i], i, c) | |
} | |
} | |
} | |
func sleepThenSay(str string, seconds int, c chan string) { | |
c <- fmt.Sprintf("sleeping for %d seconds before saying, '%s'...\n", seconds, str) | |
time.Sleep(time.Duration(seconds) * time.Second) | |
c <- fmt.Sprintf("%s\n", str) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment