Codebase list golang-github-vbauerster-mpb / f85a14a
Set current (#37) * atomic SetCurrent Vladimir Bauer authored 7 years ago GitHub committed 7 years ago
1 changed file(s) with 40 addition(s) and 19 deletion(s). Raw diff Collapse all Expand all
55 "fmt"
66 "io"
77 "io/ioutil"
8 "runtime"
89 "strings"
910 "sync"
11 "sync/atomic"
1012 "time"
1113 "unicode/utf8"
1214
4547 done chan struct{}
4648 // shutdown is closed from master Progress goroutine only
4749 shutdown chan struct{}
50
51 arbitraryCurrent struct {
52 lock uint32
53 current int64
54 }
4855 }
4956
5057 type (
181188 }
182189 }
183190
184 // SetTotal sets total dynamically.
185 // Set final to true, when total is known, it will trigger bar complete event.
186 func (b *Bar) SetTotal(total int64, final bool) bool {
187 select {
188 case b.operateState <- func(s *bState) {
189 if total > 0 {
190 s.total = total
191 }
192 if final {
193 s.current = s.total
194 s.toComplete = true
195 }
196 }:
197 return true
198 case <-b.done:
199 return false
200 }
201 }
202
203191 // SetRefill sets refill, if supported by underlying Filler.
204192 func (b *Bar) SetRefill(upto int) {
205193 b.operateState <- func(s *bState) {
207195 f.SetRefill(upto)
208196 }
209197 }
198 }
199
200 // SetTotal sets total dynamically.
201 // Set final to true, when total is known, it will trigger bar complete event.
202 func (b *Bar) SetTotal(total int64, final bool) bool {
203 select {
204 case b.operateState <- func(s *bState) {
205 if total > 0 {
206 s.total = total
207 }
208 if final {
209 s.current = s.total
210 s.toComplete = true
211 }
212 }:
213 return true
214 case <-b.done:
215 return false
216 }
217 }
218
219 // SetCurrent sets progress' current to arbitrary amount.
220 func (b *Bar) SetCurrent(current int64, wdd ...time.Duration) {
221 if current <= 0 {
222 return
223 }
224 for !atomic.CompareAndSwapUint32(&b.arbitraryCurrent.lock, 0, 1) {
225 runtime.Gosched()
226 }
227 last := b.arbitraryCurrent.current
228 b.IncrBy(int(current-last), wdd...)
229 b.arbitraryCurrent.current = current
230 atomic.StoreUint32(&b.arbitraryCurrent.lock, 0)
210231 }
211232
212233 // Increment is a shorthand for b.IncrBy(1).