Skip to content

Commit

Permalink
Context cancelling pattern with channel
Browse files Browse the repository at this point in the history
  • Loading branch information
lifthus committed Jan 24, 2023
1 parent e556a1d commit 5bf8774
Show file tree
Hide file tree
Showing 3 changed files with 63 additions and 7 deletions.
Binary file modified goContext/goContext
Binary file not shown.
26 changes: 19 additions & 7 deletions goContext/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,29 @@ package main

import (
"context"
"fmt"
"os"

"goContext/cancellingCtx"
"goContext/timeoutCtx"
)

func main() {
ss := cancellingCtx.SlowServer()
defer ss.Close()
fs := cancellingCtx.FastServer()
defer fs.Close()

ctx := context.Background()
cancellingCtx.CallBoth(ctx, os.Args[1], ss.URL, fs.URL)
switch os.Args[1] {
case "cancelling":
ss := cancellingCtx.SlowServer()
defer ss.Close()
fs := cancellingCtx.FastServer()
defer fs.Close()
ctx := context.Background()
cancellingCtx.CallBoth(ctx, os.Args[2], ss.URL, fs.URL)
case "timeout":
timeoutCtx.SimpleTimeout()
case "timeout2":
ctx := context.Background()
res, _ := timeoutCtx.LongRunningThingManager(ctx, os.Args[2])
fmt.Println(res)
default:
return
}
}
44 changes: 44 additions & 0 deletions goContext/timeoutCtx/timeoutCtx.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package timeoutCtx

import (
"context"
"fmt"
"time"
)

func SimpleTimeout() {
ctx := context.Background()
parent, cancel := context.WithTimeout(ctx, 2*time.Second)
defer cancel()
child, cancel2 := context.WithTimeout(parent, 3*time.Second)
defer cancel2()
start := time.Now()
<-child.Done()
end := time.Now()
fmt.Println(end.Sub(start))
}

func LongRunningThingManager(ctx context.Context, data string) (string, error) {
type wrapper struct {
result string
err error
}
ch := make(chan wrapper, 1)
go func() {
// do the long running jobs
result, err := longRunningThing(ctx, data)
ch <- wrapper{result, err}
}()
select {
case data := <-ch:
return data.result, data.err
case <-ctx.Done():
return "", ctx.Err()
}
}

func longRunningThing(ctx context.Context, data string) (string, error) {
time.Sleep(2 * time.Second)
fmt.Println("Done!" + data)
return "done!", nil
}

0 comments on commit 5bf8774

Please sign in to comment.