Go
package main
import (
"fmt"
"math/rand"
"sync"
"time"
"github.com/vbauerster/mpb/v8"
"github.com/vbauerster/mpb/v8/decor"
)
type File struct {
Name string
Size int
}
func main() {
rand.Seed(time.Now().UnixNano())
files := []File{
{"file-A.txt", 100},
{"file-B.txt", 80},
{"file-C.txt", 120},
}
var wg sync.WaitGroup
p := mpb.New(mpb.WithWaitGroup(&wg)) // 初始化进度管理器
for _, file := range files {
wg.Add(1)
go simulateFileRead(p, file, &wg)
}
wg.Wait()
// 给 mpb 终端输出留一帧渲染时间(重要!)
time.Sleep(100 * time.Millisecond)
fmt.Println("\n 所有文件读取完成!")
}
func simulateFileRead(p *mpb.Progress, file File, wg *sync.WaitGroup) {
defer wg.Done()
bar := p.New(
int64(file.Size),
mpb.BarStyle().Lbound("[").Filler("*").Tip(">").Padding(" ").Rbound("]"),
mpb.PrependDecorators(
decor.Name(file.Name, decor.WC{W: 12, C: decor.DSyncWidth}),
),
mpb.AppendDecorators(
decor.Percentage(decor.WC{W: 6}),
),
)
chunkSize := 5
current := 0
for current < file.Size {
time.Sleep(time.Duration(rand.Intn(100)+100) * time.Millisecond)
toAdd := chunkSize
if current+chunkSize > file.Size {
toAdd = file.Size - current
}
bar.IncrBy(toAdd)
current += toAdd
}
}
