go语言实现进度条

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
	}
}
相关推荐
程序员黄同学14 小时前
Python中的列表推导式、字典推导式和集合推导式的性能和应用场景?
开发语言·python
AI小云14 小时前
【Python高级编程】类和实例化
开发语言·人工智能·python
道之极万物灭14 小时前
Python uv虚拟环境管理工具详解
开发语言·python·uv
OC溥哥99914 小时前
C++2D地铁跑酷代码
开发语言·c++
紫荆鱼14 小时前
设计模式-状态模式(State)
c++·后端·设计模式·状态模式
「QT(C++)开发工程师」14 小时前
【LUA教程】LUA脚本语言中文教程.PDF
开发语言·pdf·lua
A接拉起00715 小时前
如何丝滑迁移 Mongodb 数据库
后端·mongodb·架构
qincloudshaw15 小时前
Linux系统下安装JDK并设置环境变量
后端
程序定小飞15 小时前
基于springboot的民宿在线预定平台开发与设计
java·开发语言·spring boot·后端·spring
天天进步201515 小时前
Python全栈项目--基于计算机视觉的车牌识别系统
开发语言·python·计算机视觉