2018-05-27 08:42:53 -04:00
|
|
|
package done
|
2018-02-08 09:39:46 -05:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2018-05-27 08:42:53 -04:00
|
|
|
// Instance is a utility for notifications of something being done.
|
|
|
|
type Instance struct {
|
2018-02-08 09:39:46 -05:00
|
|
|
access sync.Mutex
|
|
|
|
c chan struct{}
|
|
|
|
closed bool
|
|
|
|
}
|
|
|
|
|
2018-05-27 08:42:53 -04:00
|
|
|
// New returns a new Done.
|
|
|
|
func New() *Instance {
|
|
|
|
return &Instance{
|
2018-02-08 09:39:46 -05:00
|
|
|
c: make(chan struct{}),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-02-11 17:28:42 -05:00
|
|
|
// Done returns true if Close() is called.
|
2018-05-27 08:42:53 -04:00
|
|
|
func (d *Instance) Done() bool {
|
2018-02-08 09:39:46 -05:00
|
|
|
select {
|
2018-04-15 14:40:47 -04:00
|
|
|
case <-d.Wait():
|
2018-02-08 09:39:46 -05:00
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-15 14:40:47 -04:00
|
|
|
// Wait returns a channel for waiting for done.
|
2018-05-27 08:42:53 -04:00
|
|
|
func (d *Instance) Wait() <-chan struct{} {
|
2018-02-08 09:39:46 -05:00
|
|
|
return d.c
|
|
|
|
}
|
|
|
|
|
2018-03-14 22:32:10 -04:00
|
|
|
// Close marks this Done 'done'. This method may be called multiple times. All calls after first call will have no effect on its status.
|
2018-05-27 08:42:53 -04:00
|
|
|
func (d *Instance) Close() error {
|
2018-02-08 09:39:46 -05:00
|
|
|
d.access.Lock()
|
|
|
|
defer d.access.Unlock()
|
|
|
|
|
|
|
|
if d.closed {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
d.closed = true
|
|
|
|
close(d.c)
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|