Better InProgress()
Vladimir Bauer
9 years ago
| 20 | 20 | |
| 21 | 21 | // Bar represents a progress Bar |
| 22 | 22 | type Bar struct { |
| 23 | stateCh chan state | |
| 24 | incrCh chan incrReq | |
| 25 | flushedCh chan struct{} | |
| 26 | completedCh chan struct{} | |
| 27 | removeReqCh chan struct{} | |
| 28 | done chan struct{} | |
| 29 | cancel <-chan struct{} | |
| 23 | stateCh chan state | |
| 24 | incrCh chan incrReq | |
| 25 | flushedCh chan struct{} | |
| 26 | completeReqCh chan struct{} | |
| 27 | removeReqCh chan struct{} | |
| 28 | done chan struct{} | |
| 29 | completed chan struct{} | |
| 30 | cancel <-chan struct{} | |
| 30 | 31 | |
| 31 | 32 | // follawing are used after (*Bar.done) is closed |
| 32 | 33 | width int |
| 82 | 83 | |
| 83 | 84 | func newBar(id int, total int64, wg *sync.WaitGroup, conf *userConf) *Bar { |
| 84 | 85 | b := &Bar{ |
| 85 | width: conf.width, | |
| 86 | stateCh: make(chan state), | |
| 87 | incrCh: make(chan incrReq), | |
| 88 | flushedCh: make(chan struct{}), | |
| 89 | removeReqCh: make(chan struct{}), | |
| 90 | completedCh: make(chan struct{}), | |
| 91 | done: make(chan struct{}), | |
| 92 | cancel: conf.cancel, | |
| 86 | width: conf.width, | |
| 87 | stateCh: make(chan state), | |
| 88 | incrCh: make(chan incrReq), | |
| 89 | flushedCh: make(chan struct{}), | |
| 90 | removeReqCh: make(chan struct{}), | |
| 91 | completeReqCh: make(chan struct{}), | |
| 92 | done: make(chan struct{}), | |
| 93 | completed: make(chan struct{}), | |
| 94 | cancel: conf.cancel, | |
| 93 | 95 | } |
| 94 | 96 | |
| 95 | 97 | s := state{ |
| 241 | 243 | return b.getState().id |
| 242 | 244 | } |
| 243 | 245 | |
| 244 | // InProgress returns true, while progress is running | |
| 246 | // InProgress returns true, while progress is running. | |
| 245 | 247 | // Can be used as condition in for loop |
| 246 | 248 | func (b *Bar) InProgress() bool { |
| 247 | return !isClosed(b.done) | |
| 249 | select { | |
| 250 | case <-b.completed: | |
| 251 | return false | |
| 252 | default: | |
| 253 | return true | |
| 254 | } | |
| 248 | 255 | } |
| 249 | 256 | |
| 250 | 257 | // Completed signals to the bar, that process has been completed. |
| 252 | 259 | // of process completion. |
| 253 | 260 | func (b *Bar) Completed() { |
| 254 | 261 | select { |
| 255 | case b.completedCh <- struct{}{}: | |
| 262 | case b.completeReqCh <- struct{}{}: | |
| 256 | 263 | case <-b.done: |
| 257 | 264 | return |
| 258 | 265 | } |
| 321 | 328 | s.updateTimePerItemEstimate(incrStartTime, r.amount) |
| 322 | 329 | if n == s.total { |
| 323 | 330 | s.completed = true |
| 331 | close(b.completed) | |
| 324 | 332 | } |
| 325 | 333 | s.current = n |
| 326 | 334 | if r.refill != nil { |
| 332 | 340 | if s.completed { |
| 333 | 341 | return |
| 334 | 342 | } |
| 335 | case <-b.completedCh: | |
| 343 | case <-b.completeReqCh: | |
| 336 | 344 | s.completed = true |
| 337 | 345 | return |
| 338 | 346 | case <-b.removeReqCh: |