storj/private/sync2/fence.go

66 lines
1.1 KiB
Go
Raw Normal View History

2019-01-07 19:00:40 +00:00
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information
package sync2
import (
"context"
2019-01-07 19:00:40 +00:00
"sync"
)
// Fence allows to wait for something to happen.
type Fence struct {
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() {
fence.setup.Do(func() {
fence.done = make(chan struct{})
})
2019-01-07 19:00:40 +00:00
}
// Release releases everyone from Wait
func (fence *Fence) Release() {
2019-01-07 19:00:40 +00:00
fence.init()
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 {
fence.init()
select {
case <-fence.done:
return true
default:
return false
}
2019-01-07 19:00:40 +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()
return fence.done
2019-01-07 19:00:40 +00:00
}