package main
import (
"context"
"fmt"
"time"
)
func process(ctx context.Context, c <-chan int, cx2 chan int, tc chan<- []int) {
run := true
total := []int{}
for run {
select {
case val := <-c:
cx2 <- val * 2
total = append(total, val)
case <-ctx.Done():
fmt.Printf("Caught ctx\n")
run = false
close(cx2)
}
}
tc <- total
}
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 9500*time.Millisecond)
defer cancel()
c := make(chan int)
cx2 := make(chan int)
tc := make(chan []int)
go func() {
s := []int{7, 2, 8, -9, 4, 0, 5, 1}
for _, v := range s {
c <- v
time.Sleep(250*time.Millisecond)
}
}()
go process(ctx, c, cx2, tc)
run := true
for run {
select {
case val := <-cx2:
fmt.Println("double:", val)
case val := <-tc:
fmt.Println("done: ", val)
run = false
default:
}
}
}
Creative...
Today create your own program. I personally try to do this every day, as a warm up exercise. Here's the program I created today..
You can do anything you want; but, please show me the code!
repl.it