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
	}
}
相关推荐
程序猿DD几秒前
JUnit 5 中的 @ClassTemplate 实战指南
java·后端
小鸡吃米…8 分钟前
Python PyQt6教程三-菜单与工具栏
开发语言·python
aini_lovee19 分钟前
寻找 MAC 协议的 MATLAB 仿真
开发语言·macos·matlab
Victor35623 分钟前
Netty(14)如何处理Netty中的异常和错误?
后端
Victor35639 分钟前
Netty(13)Netty中的事件和回调机制
后端
Jelena157795857921 小时前
Java爬虫淘宝拍立淘item_search_img拍接口示例代码
开发语言·python
郝学胜-神的一滴1 小时前
Python数据模型:深入解析及其对Python生态的影响
开发语言·网络·python·程序人生·性能优化
一水鉴天1 小时前
整体设计 定稿 之26 重构和改造现有程序结构 之2 (codebuddy)
开发语言·人工智能·重构·架构
star _chen2 小时前
C++ std::move()详解:从小白到高手
开发语言·c++