From e3c0acfb4a705bea3e2bc3549c917f51584d8f17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Rainone?= Date: Tue, 22 Feb 2022 10:32:51 +0100 Subject: [PATCH] _example: make Work a bit more erratic --- _example/work.go | 37 +++++++++++++++++++++++++++++++------ 1 file changed, 31 insertions(+), 6 deletions(-) diff --git a/_example/work.go b/_example/work.go index 4d79c70b..da4176d1 100644 --- a/_example/work.go +++ b/_example/work.go @@ -1,18 +1,34 @@ package example import ( + "context" "fmt" + "math/rand" "time" ) -// Work loops forever, generating a bunch of allocations of various sizes in -// order to force the garbage collector to work. +// Work loops forever, generating a bunch of allocations of various sizes, plus +// some goroutines, in order to force the garbage collector to work. func Work() { + work(context.Background(), 0) +} + +func work(ctx context.Context, lvl int) { + println("work", lvl) m := make(map[int]interface{}) + tick := time.NewTicker(10 * time.Millisecond) + for i := 0; ; i++ { + select { + case <-ctx.Done(): + return + case <-tick.C: + break + } var obj interface{} - switch i % 6 { + + switch rand.Intn(10) % 10 { case 0: obj = &struct { _ uint32 @@ -26,10 +42,20 @@ func Work() { obj = fmt.Sprintf("a relatively long and useless string %d", i) case 3: obj = make([]byte, i%1024) - case 4: + case 4, 5: obj = make([]byte, 10*i%1024) - case 5: + case 6, 7: obj = make([]string, 512) + case 8: + obj = make([]byte, 16*1024) + case 9: + if lvl > 2 { + break + } + // Sometimes start another goroutine, just because... + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) + defer cancel() + work(ctx, lvl+1) } if i == 1000 { @@ -38,6 +64,5 @@ func Work() { } m[i] = obj - time.Sleep(10 * time.Millisecond) } }