2019-01-07 19:00:40 +00:00
|
|
|
// Copyright (C) 2019 Storj Labs, Inc.
|
|
|
|
// See LICENSE for copying information
|
|
|
|
|
|
|
|
package sync2
|
|
|
|
|
|
|
|
import (
|
2019-10-28 14:04:31 +00:00
|
|
|
"context"
|
2019-01-07 19:00:40 +00:00
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Fence allows to wait for something to happen.
|
|
|
|
type Fence struct {
|
2019-10-28 14:04:31 +00:00
|
|
|
setup sync.Once
|
|
|
|
release sync.Once
|
|
|
|
done chan struct{}
|
2019-01-07 19:00:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// init sets up the initial lock into wait
|
|
|
|
func (fence *Fence) init() {
|
2019-10-28 14:04:31 +00:00
|
|
|
fence.setup.Do(func() {
|
|
|
|
fence.done = make(chan struct{})
|
|
|
|
})
|
2019-01-07 19:00:40 +00:00
|
|
|
}
|
|
|
|
|
2019-10-28 14:04:31 +00:00
|
|
|
// Release releases everyone from Wait
|
|
|
|
func (fence *Fence) Release() {
|
2019-01-07 19:00:40 +00:00
|
|
|
fence.init()
|
2019-10-28 14:04:31 +00:00
|
|
|
fence.release.Do(func() { close(fence.done) })
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait waits for wait to be unlocked.
|
|
|
|
// Returns true when it was successfully released.
|
|
|
|
func (fence *Fence) Wait(ctx context.Context) bool {
|
|
|
|
fence.init()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-fence.done:
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return false
|
|
|
|
case <-fence.done:
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
2019-01-07 19:00:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Released returns whether the fence has been released.
|
|
|
|
func (fence *Fence) Released() bool {
|
2019-10-28 14:04:31 +00:00
|
|
|
fence.init()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-fence.done:
|
|
|
|
return true
|
|
|
|
default:
|
|
|
|
return false
|
|
|
|
}
|
2019-01-07 19:00:40 +00:00
|
|
|
}
|
|
|
|
|
2019-10-28 14:04:31 +00:00
|
|
|
// Done returns channel that will be closed when the fence is released.
|
|
|
|
func (fence *Fence) Done() chan struct{} {
|
2019-01-07 19:00:40 +00:00
|
|
|
fence.init()
|
2019-10-28 14:04:31 +00:00
|
|
|
return fence.done
|
2019-01-07 19:00:40 +00:00
|
|
|
}
|