Created
March 30, 2022 15:52
-
-
Save tanema/398b0770be60ba8d1dca7387586b5e89 to your computer and use it in GitHub Desktop.
The most simple threadsafe progress bar in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package hershey | |
import ( | |
"fmt" | |
"math" | |
"strings" | |
"sync" | |
"time" | |
) | |
type Bar struct { | |
mut sync.Mutex | |
percent int | |
current int | |
total int | |
} | |
func New(total int) *Bar { | |
return &Bar{total: total, current: 0, percent: 0} | |
} | |
func (bar *Bar) Done(n int) { | |
bar.mut.Lock() | |
defer bar.mut.Unlock() | |
bar.current += n | |
bar.percent = int(math.Min(100, (float64(bar.current)/float64(bar.total))*100)) | |
fmt.Printf("\r[%-50s]%3d%% %8d/%d", strings.Repeat("=", bar.percent/2), bar.percent, bar.current, bar.total) | |
} | |
func (bar *Bar) Finish() { | |
bar.current = bar.total | |
fmt.Println() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment