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 小时前
FreeRTOS 在 RISC-V 上是如何“点火“的 —— 从 main() 到第一个任务的完整链路
java·开发语言·risc-v
张宇Joaquin4 小时前
鲲鹏统一并行加速库KUPL--众核并行能力介绍
java·开发语言·网络
736c4 小时前
C语言-数组 07
c语言·开发语言
宸津-代码粉碎机4 小时前
AI攻防战升级!基于Spring AI构建Java应用自动免疫安全体系
java·大数据·开发语言·人工智能·python·安全·spring
朦胧之5 小时前
PostgreSQL 数据库笔记
人工智能·后端
xcLeigh6 小时前
Go入门:整数类型的溢出与安全边界
java·安全·golang
LorryJovens6 小时前
【LAAP科研】CEN因果等价网络理论---从双缝干涉到因果等价
开发语言·php
Brilliantwxx6 小时前
【Linux】 进程(10) 进程控制深度解析:创建、终止与等待
linux·运维·服务器·c语言·开发语言·网络
卢锡荣7 小时前
国产PD3.1全集成Type-C管控芯片LDR6020P
c语言·开发语言
IT_陈寒7 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端