Created
December 18, 2024 13:43
-
-
Save niksteff/0966d0700b811f692002ab6a1163b68e to your computer and use it in GitHub Desktop.
Just a play projec to check context behaviour
This file contains 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 gocontext | |
import ( | |
"context" | |
"log/slog" | |
"sync" | |
"testing" | |
"time" | |
) | |
func TestContext(t *testing.T) { | |
ctx, cancel := context.WithCancel(context.Background()) | |
var wg sync.WaitGroup | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
err := Foo(ctx) | |
if err != nil { | |
slog.Warn("error from Foo()", slog.String("error", err.Error())) | |
} | |
}() | |
wg.Add(1) | |
go func() { | |
defer wg.Done() | |
err := Bar(ctx) | |
if err != nil { | |
slog.Warn("error from Bar()", slog.String("error", err.Error())) | |
} | |
}() | |
go func() { | |
select { | |
case <-ctx.Done(): | |
slog.Info("exiting test ...") | |
return | |
} | |
}() | |
wg.Wait() | |
cancel() | |
time.Sleep(5 * time.Second) | |
} | |
func Foo(ctx context.Context) error { | |
ctx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
defer cancel() | |
tick := time.NewTicker(1 * time.Minute) | |
defer tick.Stop() | |
select { | |
case <-ctx.Done(): | |
return ctx.Err() | |
case <-tick.C: | |
slog.Info("tick tock ...") | |
} | |
return nil | |
} | |
func Bar(ctx context.Context) error { | |
ctx, cancel := context.WithTimeout(ctx, 5*time.Second) | |
defer cancel() | |
v := 0 | |
for { | |
select { | |
case <-ctx.Done(): | |
return ctx.Err() | |
default: | |
v += 1 | |
slog.Info("counter", slog.Int("value", v)) | |
time.Sleep(1 * time.Second) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment