Skip to content

Instantly share code, notes, and snippets.

@zapkub
Created November 19, 2018 11:20
Show Gist options
  • Save zapkub/236d29d3987c52b02a3de73944cc75c4 to your computer and use it in GitHub Desktop.
Save zapkub/236d29d3987c52b02a3de73944cc75c4 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"time"
)
func perform(ctx *context.Context, name string, out chan<- string) {
for {
if ctx != nil {
select {
case t := <-time.After(time.Second):
fmt.Printf("\n%d\n", t.Second())
// just continue here
case <-(*ctx).Done():
return
case out <- name:
// return name on chan
}
} else {
fmt.Println(name)
time.Sleep(time.Second)
}
}
}
func start() {
duration, err := time.ParseDuration("5s")
if err != nil {
panic(err)
}
performOut := make(chan string)
ctx, cancel := context.WithTimeout(context.Background(), duration)
defer func() {
fmt.Println("Cancel routines")
cancel()
}()
perform(&ctx, "routines", performOut)
}
func main() {
go start()
perform(nil, "main", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment