Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Swaps mutex for atomic in ingester's OnceSwitch #3141

Merged
merged 1 commit into from
Jan 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 12 additions & 17 deletions pkg/ingester/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/prometheus/prometheus/pkg/labels"
tsdb_record "github.com/prometheus/prometheus/tsdb/record"
"github.com/weaveworks/common/httpgrpc"
"go.uber.org/atomic"

"github.com/cortexproject/cortex/pkg/ingester/client"
"github.com/cortexproject/cortex/pkg/ingester/index"
Expand Down Expand Up @@ -600,32 +601,26 @@ func shouldConsiderStream(stream *stream, req *logproto.SeriesRequest) bool {
return false
}

// OnceSwitch is a write optimized switch that can only ever be switched "on".
// It uses a RWMutex underneath the hood to quickly and effectively (in a concurrent environment)
// check if the switch has already been triggered, only actually acquiring the mutex for writing if not.
// OnceSwitch is an optimized switch that can only ever be switched "on" in a concurrent environment.
type OnceSwitch struct {
sync.RWMutex
toggle bool
triggered atomic.Bool
}

func (o *OnceSwitch) Get() bool {
o.RLock()
defer o.RUnlock()
return o.toggle
return o.triggered.Load()
}

func (o *OnceSwitch) Trigger() {
o.TriggerAnd(nil)
}

// TriggerAnd will ensure the switch is on and run the provided function if
// the switch was not already toggled on.
func (o *OnceSwitch) TriggerAnd(fn func()) {
o.RLock()
if o.toggle {
o.RUnlock()
return

triggeredPrior := o.triggered.Swap(true)
if !triggeredPrior && fn != nil {
fn()
}

o.RUnlock()
o.Lock()
o.toggle = true
o.Unlock()
fn()
}
25 changes: 25 additions & 0 deletions pkg/ingester/instance_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"fmt"
"math/rand"
"runtime"
"sort"
"sync"
"testing"
Expand Down Expand Up @@ -334,3 +335,27 @@ func Benchmark_instance_addNewTailer(b *testing.B) {
})

}

func Benchmark_OnceSwitch(b *testing.B) {
threads := runtime.GOMAXPROCS(0)

// limit threads
if threads > 4 {
threads = 4
}

for n := 0; n < b.N; n++ {
x := &OnceSwitch{}
var wg sync.WaitGroup
for i := 0; i < threads; i++ {
wg.Add(1)
go func() {
for i := 0; i < 1000; i++ {
x.Trigger()
}
wg.Done()
}()
}
wg.Wait()
}
}