Codebase list golang-github-vbauerster-mpb / 0db6716
refactoring complex example Vladimir Bauer 4 years ago
1 changed file(s) with 14 addition(s) and 27 deletion(s). Raw diff Collapse all Expand all
22 import (
33 "fmt"
44 "math/rand"
5 "sync"
65 "time"
76
87 "github.com/vbauerster/mpb/v7"
1413 }
1514
1615 func main() {
17 doneWg := new(sync.WaitGroup)
18 // passed doneWg will be accounted at p.Wait() call
19 p := mpb.New(mpb.WithWaitGroup(doneWg))
2016 numBars := 4
17 bars := make([]*mpb.Bar, numBars)
18 p := mpb.New()
2119
22 var bars []*mpb.Bar
23 var downloadWgg []*sync.WaitGroup
2420 for i := 0; i < numBars; i++ {
25 wg := new(sync.WaitGroup)
26 wg.Add(1)
27 downloadWgg = append(downloadWgg, wg)
2821 task := fmt.Sprintf("Task#%02d:", i)
29 job := "downloading"
30 b := p.AddBar(rand.Int63n(201)+100,
22 bars[i] = p.AddBar(rand.Int63n(201)+100,
3123 mpb.PrependDecorators(
3224 decor.Name(task, decor.WC{W: len(task) + 1, C: decor.DidentRight}),
33 decor.Name(job, decor.WCSyncSpaceR),
25 decor.Name("downloading", decor.WCSyncSpaceR),
3426 decor.CountersNoUnit("%d / %d", decor.WCSyncWidth),
3527 ),
3628 mpb.AppendDecorators(decor.Percentage(decor.WC{W: 5})),
3729 )
38 go newTask(wg, b, i+1)
39 bars = append(bars, b)
30 go complete(bars[i], i+1)
4031 }
4132
4233 for i := 0; i < numBars; i++ {
43 doneWg.Add(1)
44 i := i
34 afterBar := bars[i]
35 task := fmt.Sprintf("Task#%02d:", i)
36 incrBy := numBars - i
4537 go func() {
46 task := fmt.Sprintf("Task#%02d:", i)
47 // ANSI escape sequences are not supported on Windows OS
48 job := "\x1b[31;1;4mつのだ☆HIRO\x1b[0m"
49 // preparing delayed bars
38 job := "\x1b[31minstalling\x1b[0m"
39 // preparing queued bars
5040 b := p.AddBar(rand.Int63n(101)+100,
51 mpb.BarQueueAfter(bars[i]),
41 mpb.BarQueueAfter(afterBar),
5242 mpb.BarFillerClearOnComplete(),
5343 mpb.PrependDecorators(
5444 decor.Name(task, decor.WC{W: len(task) + 1, C: decor.DidentRight}),
5949 decor.OnComplete(decor.Percentage(decor.WC{W: 5}), ""),
6050 ),
6151 )
62 // waiting for download to complete, before starting install job
63 downloadWgg[i].Wait()
64 go newTask(doneWg, b, numBars-i)
52 complete(b, incrBy) // blocks until afterBar completes
6553 }()
6654 }
67 // wait for passed doneWg and for all bars to complete and flush
55
6856 p.Wait()
6957 }
7058
71 func newTask(wg *sync.WaitGroup, bar *mpb.Bar, incrBy int) {
72 defer wg.Done()
59 func complete(bar *mpb.Bar, incrBy int) {
7360 max := 100 * time.Millisecond
7461 for !bar.Completed() {
7562 // start variable is solely for EWMA calculation