Fix race in Progress shutdown where some messages could have been lost.

This commit is contained in:
Andrey Smirnov
2014-02-27 22:52:11 +04:00
parent 268128482c
commit d251a519b6

View File

@@ -12,6 +12,7 @@ const (
codePrint = iota codePrint = iota
codeProgress codeProgress
codeHideProgress codeHideProgress
codeStop
) )
type printTask struct { type printTask struct {
@@ -37,7 +38,6 @@ var (
// NewProgress creates new progress instance // NewProgress creates new progress instance
func NewProgress() *Progress { func NewProgress() *Progress {
return &Progress{ return &Progress{
stop: make(chan bool),
stopped: make(chan bool), stopped: make(chan bool),
queue: make(chan printTask, 100), queue: make(chan printTask, 100),
} }
@@ -51,7 +51,7 @@ func (p *Progress) Start() {
// Shutdown shuts down progress display // Shutdown shuts down progress display
func (p *Progress) Shutdown() { func (p *Progress) Shutdown() {
p.ShutdownBar() p.ShutdownBar()
p.stop <- true p.queue <- printTask{code: codeStop}
<-p.stopped <-p.stopped
} }
@@ -136,27 +136,25 @@ func (p *Progress) ColoredPrintf(msg string, a ...interface{}) {
func (p *Progress) worker() { func (p *Progress) worker() {
for { for {
select { task := <-p.queue
case task := <-p.queue: switch task.code {
switch task.code { case codePrint:
case codePrint: if p.barShown {
if p.barShown { fmt.Print("\r\033[2K")
fmt.Print("\r\033[2K") p.barShown = false
p.barShown = false
}
fmt.Print(task.message)
case codeProgress:
if p.bar != nil {
fmt.Print("\r" + task.message)
p.barShown = true
}
case codeHideProgress:
if p.barShown {
fmt.Print("\r\033[2K")
p.barShown = false
}
} }
case <-p.stop: fmt.Print(task.message)
case codeProgress:
if p.bar != nil {
fmt.Print("\r" + task.message)
p.barShown = true
}
case codeHideProgress:
if p.barShown {
fmt.Print("\r\033[2K")
p.barShown = false
}
case codeStop:
p.stopped <- true p.stopped <- true
return return
} }