Created
November 22, 2017 23:03
-
-
Save mettledrum/25b950b200a15f526f80960cd2721944 to your computer and use it in GitHub Desktop.
hard workin go routines
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" | |
"os" | |
"os/signal" | |
"syscall" | |
"time" | |
) | |
func work() { | |
fmt.Println("workin' hard") | |
time.Sleep(4 * time.Second) | |
} | |
func main() { | |
// needs to be buffered so we can exit | |
// if this is unbuffered, ^C never reaches closing time | |
kc := make(chan os.Signal, 1) | |
signal.Notify(kc, syscall.SIGINT, syscall.SIGTERM) | |
ch := make(chan bool) | |
go func() { | |
for { | |
ch <- false | |
time.Sleep(3 * time.Second) // work is coming in faster than the worker can handle it! | |
} | |
}() | |
for { | |
select { | |
case <-kc: | |
fmt.Println("closing time") | |
return | |
case <-ch: | |
work() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment