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
	}
}
相关推荐
码兄科技3 小时前
实战:基于Spring Boot + UniApp的地理信息小程序开发
spring boot·后端·uni-app
程序喵大人4 小时前
【C++进阶】STL容器与迭代器 - 01 STL 容器先解决元素放在哪里
开发语言·c++·stl
cui_ruicheng4 小时前
Python从入门到实战(十六):多进程编程
开发语言·python
腾讯云云开发5 小时前
腾讯云 CloudBase 登上 WAIC:我们为 Agent 重新设计了云的生产线
后端
星栈5 小时前
从装一堆工具到看懂 Node 工程化思维:我的项目复盘记录
后端·node.js
65岁退休Coder5 小时前
LangChain v1.3.4 笔记 - 05 Agent 上下文记忆
后端
颜酱6 小时前
04 | 召回前置准备:搭好召回所需的四个数据库
前端·人工智能·后端
wdfk_prog6 小时前
嵌入式面试真题第 15 题:不可恢复异常后的通用崩溃快照、调用栈保存与离线分析架构
linux·开发语言·面试·架构
JaneConan6 小时前
鸿蒙 韶非 UI 系列:能力调用 startAbilityForResult,跳能力拿回参,鸿蒙能力路由入门
后端·harmonyos
晴空了无痕6 小时前
从 Go 基础到 K8s:一条可落地的 Go 服务端成长路线
开发语言·后端·golang·kubernetes