diff --git a/priority-queue.go b/priority-queue.go index 99a9234..f60e222 100644 --- a/priority-queue.go +++ b/priority-queue.go @@ -38,3 +38,33 @@ bar.priority = priority heap.Fix(pq, bar.index) } + +func (pq priorityQueue) maxNumP() int { + if pq.Len() == 0 { + return 0 + } + + max := pq[0].NumOfPrependers() + for i := 1; i < pq.Len(); i++ { + n := pq[i].NumOfPrependers() + if n > max { + max = n + } + } + return max +} + +func (pq priorityQueue) maxNumA() int { + if pq.Len() == 0 { + return 0 + } + + max := pq[0].NumOfAppenders() + for i := 1; i < pq.Len(); i++ { + n := pq[i].NumOfAppenders() + if n > max { + max = n + } + } + return max +} diff --git a/progress.go b/progress.go index 150d274..363b084 100644 --- a/progress.go +++ b/progress.go @@ -37,6 +37,7 @@ // progress state, which may contain several bars pState struct { bHeap *priorityQueue + heapUpdated bool idCounter int width int format string @@ -98,6 +99,7 @@ options = append(options, barWidth(s.width), barFormat(s.format)) b := newBar(s.idCounter, total, p.wg, s.cancel, options...) heap.Push(s.bHeap, b) + s.heapUpdated = true s.idCounter++ result <- b }: @@ -112,8 +114,13 @@ result := make(chan bool, 1) select { case p.operateState <- func(s *pState) { - b.Complete() - result <- heap.Remove(s.bHeap, b.index) != nil + if heap.Remove(s.bHeap, b.index) != nil { + s.heapUpdated = true + b.Complete() + result <- true + } else { + result <- false + } }: return <-result case <-p.quit: @@ -212,10 +219,6 @@ } func (s *pState) writeAndFlush(tw, numP, numA int) (err error) { - if numP < 0 && numA < 0 { - return - } - wSyncTimeout := make(chan struct{}) time.AfterFunc(s.rr, func() { close(wSyncTimeout) diff --git a/progress_posix.go b/progress_posix.go index 1a3db11..7a8027e 100644 --- a/progress_posix.go +++ b/progress_posix.go @@ -25,11 +25,10 @@ close(p.done) }() - numP, numA := -1, -1 - + var numP, numA int var timer *time.Timer var resumeTicker <-chan time.Time - resumeDelay := 300 * time.Millisecond + resumeDelay := 320 * time.Millisecond for { select { @@ -40,12 +39,10 @@ runtime.Gosched() break } - b0 := (*s.bHeap)[0] - if numP == -1 { - numP = b0.NumOfPrependers() - } - if numA == -1 { - numA = b0.NumOfAppenders() + if s.heapUpdated { + numP = s.bHeap.maxNumP() + numA = s.bHeap.maxNumA() + s.heapUpdated = false } tw, _, _ := cwriter.TermSize() err := s.writeAndFlush(tw, numP, numA) diff --git a/progress_windows.go b/progress_windows.go index 9b16ff6..907d8bb 100644 --- a/progress_windows.go +++ b/progress_windows.go @@ -18,7 +18,7 @@ close(p.done) }() - numP, numA := -1, -1 + var numP, numA int for { select { @@ -29,12 +29,10 @@ runtime.Gosched() break } - b0 := (*s.bHeap)[0] - if numP == -1 { - numP = b0.NumOfPrependers() - } - if numA == -1 { - numA = b0.NumOfAppenders() + if s.heapUpdated { + numP = s.bHeap.maxNumP() + numA = s.bHeap.maxNumA() + s.heapUpdated = false } tw, _, _ := cwriter.TermSize() err := s.writeAndFlush(tw, numP, numA)