Codebase list golang-github-vbauerster-mpb / 94d5824
update PrependFunc and AppendFunc examples Vladimir Bauer 9 years ago
1 changed file(s) with 37 addition(s) and 10 deletion(s). Raw diff Collapse all Expand all
22 import (
33 "fmt"
44 "math/rand"
5 "sync"
56 "time"
67 "unicode/utf8"
78
5152 func ExampleBar_PrependFunc() {
5253 decor := func(s *mpb.Statistics, myWidth chan<- int, maxWidth <-chan int) string {
5354 str := fmt.Sprintf("%3d/%3d", s.Current, s.Total)
55 // send width to Progress' goroutine
5456 myWidth <- utf8.RuneCountInString(str)
57 // receive max width
5558 max := <-maxWidth
5659 return fmt.Sprintf(fmt.Sprintf("%%%ds", max+1), str)
5760 }
5861
5962 totalItem := 100
63 var wg sync.WaitGroup
6064 p := mpb.New()
61 bar := p.AddBar(int64(totalItem)).PrependFunc(decor)
62
63 for i := 0; i < totalItem; i++ {
64 bar.Incr(1) // increment progress bar
65 time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
65 wg.Add(3) // add wg delta
66 for i := 0; i < 3; i++ {
67 name := fmt.Sprintf("Bar#%d:", i)
68 bar := p.AddBar(int64(totalItem)).
69 PrependName(name, len(name), 0).
70 PrependFunc(decor)
71 go func() {
72 defer wg.Done()
73 for i := 0; i < totalItem; i++ {
74 bar.Incr(1)
75 time.Sleep(time.Duration(rand.Intn(totalItem)) * time.Millisecond)
76 }
77 }()
6678 }
79 wg.Wait() // Wait for goroutines to finish
80 p.Stop() // Stop mpb's rendering goroutine
6781 }
6882
6983 func ExampleBar_AppendFunc() {
7084 decor := func(s *mpb.Statistics, myWidth chan<- int, maxWidth <-chan int) string {
7185 str := fmt.Sprintf("%3d/%3d", s.Current, s.Total)
86 // send width to Progress' goroutine
7287 myWidth <- utf8.RuneCountInString(str)
88 // receive max width
7389 max := <-maxWidth
7490 return fmt.Sprintf(fmt.Sprintf("%%%ds", max+1), str)
7591 }
7692
7793 totalItem := 100
94 var wg sync.WaitGroup
7895 p := mpb.New()
79 bar := p.AddBar(int64(totalItem)).AppendFunc(decor)
80
81 for i := 0; i < totalItem; i++ {
82 bar.Incr(1) // increment progress bar
83 time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
96 wg.Add(3) // add wg delta
97 for i := 0; i < 3; i++ {
98 name := fmt.Sprintf("Bar#%d:", i)
99 bar := p.AddBar(int64(totalItem)).
100 PrependName(name, len(name), 0).
101 AppendFunc(decor)
102 go func() {
103 defer wg.Done()
104 for i := 0; i < totalItem; i++ {
105 bar.Incr(1)
106 time.Sleep(time.Duration(rand.Intn(totalItem)) * time.Millisecond)
107 }
108 }()
84109 }
110 wg.Wait() // Wait for goroutines to finish
111 p.Stop() // Stop mpb's rendering goroutine
85112 }