In the below program, there is a select sequence in both C1 & C2. A deadline context for 1.5 seconds is defined in C1, which after the deadline, cancels the context, leads to ctx.Done() and prevents the reading of integers in C2 which would further cancel the context and lead to ctx.Done() in C1.
If that is the case then what use is cancelCtx() in C1 when the context is already being cancelled?
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx := context.Background()
C1(ctx)
}
func C1(ctx context.Context) {
deadline := time.Now().Add(1500 * time.Millisecond)
ctx, cancelCtx := context.WithDeadline(ctx, deadline)
printCh := make(chan int)
go C2(ctx, printCh)
for num := 1; num <= 3; num++ {
select {
case printCh <- num:
time.Sleep(1 * time.Second)
case <-ctx.Done():
fmt.Printf("C1: Finished\n")
}
}
cancelCtx()
time.Sleep(100 * time.Millisecond)
}
func C2(ctx context.Context, printCh <-chan int) {
for {
select {
case num := <-printCh:
fmt.Printf("C2: %d\n", num)
case <-ctx.Done():
if err := ctx.Err(); err != nil {
fmt.Printf("C2 Error: %s\n", err)
}
fmt.Printf("C2: Finished\n")
return
}
}
}