Skip to content

Commit

Permalink
need to lock the mutex state around adding
Browse files Browse the repository at this point in the history
  • Loading branch information
lhopki01 committed Jun 1, 2019
1 parent 07ba2d7 commit af7d746
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 17 deletions.
23 changes: 6 additions & 17 deletions progressbar.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,20 +248,20 @@ func (p *ProgressBar) Finish() error {
return p.Add(0)
}

// Add with increase the current count on the progress bar
func (p *ProgressBar) Set(num int) error {
return p.Set64(int64(num))
// Add will add the specified amount to the progressbar
func (p *ProgressBar) Add(num int) error {
return p.Add64(int64(num))
}

// Add with increase the current count on the progress bar
func (p *ProgressBar) Set64(num int64) error {
// Add64 will add the specified amount to the progressbar
func (p *ProgressBar) Add64(num int64) error {
p.lock.Lock()
defer p.lock.Unlock()

if p.config.max == 0 {
return errors.New("max must be greater than 0")
}
p.state.currentNum = num
p.state.currentNum += num
percent := float64(p.state.currentNum) / float64(p.config.max)
p.state.currentSaucerSize = int(percent * float64(p.config.width))
p.state.currentPercent = int(percent * 100)
Expand All @@ -281,16 +281,6 @@ func (p *ProgressBar) Set64(num int64) error {
return nil
}

// Add will add the specified amount to the progressbar
func (p *ProgressBar) Add(num int) error {
return p.Add64(int64(num))
}

// Add64 will add the specified amount to the progressbar
func (p *ProgressBar) Add64(num int64) error {
return p.Set64(p.state.currentNum + num)
}

// Clear erases the progress bar from the current line
func (p *ProgressBar) Clear() error {
return clearProgressBar(p.config, p.state)
Expand Down Expand Up @@ -468,7 +458,6 @@ type Reader struct {
bar *ProgressBar
}


// Read will read the data and add the number of bytes to the progressbar
func (r *Reader) Read(p []byte) (n int, err error) {
n, err = r.Reader.Read(p)
Expand Down
21 changes: 21 additions & 0 deletions progressbar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"net/http"
"os"
"strings"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -209,6 +210,26 @@ func TestReaderToFile(t *testing.T) {
assert.Nil(t, os.Remove("croc_v4.1.4_Windows-64bit_GUI.zip"))
}

func TestConcurrency(t *testing.T) {
buf := strings.Builder{}
bar := NewOptions(
1000,
OptionSetWriter(&buf),
)
var wg sync.WaitGroup
for i := 0; i < 900; i++ {
wg.Add(1)
go func(b *ProgressBar, wg *sync.WaitGroup) {
bar.Add(1)
wg.Done()
}(bar, &wg)
}
wg.Wait()
result := bar.state.currentNum
expect := int64(900)
assert.Equal(t, expect, result)
}

func md5sum(filePath string) (result string, err error) {
file, err := os.Open(filePath)
if err != nil {
Expand Down

0 comments on commit af7d746

Please sign in to comment.