Created
December 3, 2023 05:11
-
-
Save neilotoole/0c799d06ef9d47458328bdfd6054790a to your computer and use it in GitHub Desktop.
mpb render delay bug example
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 main | |
import ( | |
"context" | |
"fmt" | |
"math/rand" | |
"sync" | |
"time" | |
"github.com/vbauerster/mpb/v8" | |
"github.com/vbauerster/mpb/v8/decor" | |
) | |
func main() { | |
const delay = time.Second * 10 | |
var wg sync.WaitGroup | |
// passed wg will be accounted at p.Wait() call | |
p := mpb.New(mpb.WithWaitGroup(&wg), mpb.WithRenderDelay(renderDelay(context.Background(), delay))) | |
total, numBars := 100, 3 | |
wg.Add(numBars) | |
for i := 0; i < numBars; i++ { | |
name := fmt.Sprintf("Bar#%d:", i) | |
bar := p.AddBar(int64(total), | |
mpb.PrependDecorators( | |
decor.Name(name), | |
decor.Percentage(decor.WCSyncSpace), | |
), | |
) | |
// simulating some work | |
go func() { | |
defer wg.Done() | |
rng := rand.New(rand.NewSource(time.Now().UnixNano())) | |
max := 100 * time.Millisecond | |
for i := 0; i < total; i++ { | |
time.Sleep(time.Duration(rng.Intn(10)+1) * max / 10) | |
bar.IncrBy(i) | |
} | |
bar.Abort(true) // BAD: Causes a render even if render delay hasn't expired. | |
}() | |
} | |
// wait for passed wg and for all bars to complete and flush | |
p.Wait() | |
} | |
// renderDelay returns a channel that will be closed after d, | |
// or if ctx is done. | |
func renderDelay(ctx context.Context, d time.Duration) <-chan struct{} { | |
ch := make(chan struct{}) | |
t := time.NewTimer(d) | |
go func() { | |
defer close(ch) | |
defer t.Stop() | |
select { | |
case <-ctx.Done(): | |
case <-t.C: | |
} | |
}() | |
return ch | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment