Created
November 19, 2018 11:20
-
-
Save zapkub/236d29d3987c52b02a3de73944cc75c4 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 ( | |
"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