diff --git a/example56-context-timeout/solution01/go.mod b/example56-context-timeout/solution01/go.mod new file mode 100644 index 0000000..3f0e511 --- /dev/null +++ b/example56-context-timeout/solution01/go.mod @@ -0,0 +1,3 @@ +module example + +go 1.23.1 diff --git a/example56-context-timeout/solution01/main.go b/example56-context-timeout/solution01/main.go new file mode 100644 index 0000000..9afec49 --- /dev/null +++ b/example56-context-timeout/solution01/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "time" +) + +func main() { + output := make(chan int, 30) + + go func() { + for i := 0; i < 30; i++ { + output <- i + time.Sleep(100 * time.Millisecond) + } + }() + + timeout := time.After(1 * time.Second) + // how to fix the timeout issue? + for { + select { + case val := <-output: + select { + case <-timeout: + println("reached timeout, but still have data to process") + return + default: + } + // simulate slow consumer + time.Sleep(500 * time.Millisecond) + println("output:", val) + // how to fix the timeout issue? + case <-timeout: + println("timeout") + return + } + } +} diff --git a/example56-context-timeout/solution02/go.mod b/example56-context-timeout/solution02/go.mod new file mode 100644 index 0000000..3f0e511 --- /dev/null +++ b/example56-context-timeout/solution02/go.mod @@ -0,0 +1,3 @@ +module example + +go 1.23.1 diff --git a/example56-context-timeout/solution02/main.go b/example56-context-timeout/solution02/main.go new file mode 100644 index 0000000..f7a3b08 --- /dev/null +++ b/example56-context-timeout/solution02/main.go @@ -0,0 +1,37 @@ +package main + +import ( + "context" + "time" +) + +func main() { + output := make(chan int, 30) + + go func() { + for i := 0; i < 30; i++ { + output <- i + time.Sleep(100 * time.Millisecond) + } + }() + + ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) + defer cancel() + // how to fix the timeout issue? + for { + select { + case val := <-output: + if ctx.Err() != nil { + println("reached timeout, but still have data to process") + return + } + // simulate slow consumer + time.Sleep(500 * time.Millisecond) + println("output:", val) + // how to fix the timeout issue? + case <-ctx.Done(): + println("timeout") + return + } + } +}