cancel example
Vladimir Bauer
9 years ago
| 0 | package main | |
| 1 | ||
| 2 | import ( | |
| 3 | "context" | |
| 4 | "fmt" | |
| 5 | "math/rand" | |
| 6 | "sync" | |
| 7 | "time" | |
| 8 | ||
| 9 | "github.com/vbauerster/mpb" | |
| 10 | ) | |
| 11 | ||
| 12 | const ( | |
| 13 | maxBlockSize = 12 | |
| 14 | ) | |
| 15 | ||
| 16 | func main() { | |
| 17 | ||
| 18 | var wg sync.WaitGroup | |
| 19 | ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) | |
| 20 | defer cancel() | |
| 21 | p := mpb.New(ctx).SetWidth(64) | |
| 22 | ||
| 23 | name1 := "Bar#1: " | |
| 24 | bar1 := p.AddBar(50). | |
| 25 | PrependName(name1, len(name1)).PrependETA(4). | |
| 26 | AppendPercentage().TrimRightSpace() | |
| 27 | wg.Add(1) | |
| 28 | go func() { | |
| 29 | defer wg.Done() | |
| 30 | blockSize := rand.Intn(maxBlockSize) + 1 | |
| 31 | for i := 0; i < 50; i++ { | |
| 32 | select { | |
| 33 | case <-ctx.Done(): | |
| 34 | return | |
| 35 | default: | |
| 36 | sleep(blockSize) | |
| 37 | bar1.Incr(1) | |
| 38 | blockSize = rand.Intn(maxBlockSize) + 1 | |
| 39 | } | |
| 40 | } | |
| 41 | }() | |
| 42 | ||
| 43 | bar2 := p.AddBar(100). | |
| 44 | PrependName("", 0-len(name1)).PrependETA(4). | |
| 45 | AppendPercentage().TrimRightSpace() | |
| 46 | wg.Add(1) | |
| 47 | go func() { | |
| 48 | defer wg.Done() | |
| 49 | blockSize := rand.Intn(maxBlockSize) + 1 | |
| 50 | for i := 0; i < 100; i++ { | |
| 51 | select { | |
| 52 | case <-ctx.Done(): | |
| 53 | return | |
| 54 | default: | |
| 55 | sleep(blockSize) | |
| 56 | bar2.Incr(1) | |
| 57 | blockSize = rand.Intn(maxBlockSize) + 1 | |
| 58 | } | |
| 59 | } | |
| 60 | }() | |
| 61 | ||
| 62 | bar3 := p.AddBar(80). | |
| 63 | PrependName("Bar#3: ", 0).PrependETA(4). | |
| 64 | AppendPercentage().TrimRightSpace() | |
| 65 | wg.Add(1) | |
| 66 | go func() { | |
| 67 | defer wg.Done() | |
| 68 | blockSize := rand.Intn(maxBlockSize) + 1 | |
| 69 | for i := 0; i < 80; i++ { | |
| 70 | select { | |
| 71 | case <-ctx.Done(): | |
| 72 | return | |
| 73 | default: | |
| 74 | sleep(blockSize) | |
| 75 | bar3.Incr(1) | |
| 76 | blockSize = rand.Intn(maxBlockSize) + 1 | |
| 77 | } | |
| 78 | } | |
| 79 | }() | |
| 80 | ||
| 81 | wg.Wait() | |
| 82 | p.Stop() | |
| 83 | // p.AddBar(2) // panic: you cannot reuse p, create new one! | |
| 84 | fmt.Println("stop") | |
| 85 | } | |
| 86 | ||
| 87 | func sleep(blockSize int) { | |
| 88 | time.Sleep(time.Duration(blockSize) * (50*time.Millisecond + time.Duration(rand.Intn(5*int(time.Millisecond))))) | |
| 89 | } |