fixed data races

This commit is contained in:
Maksadbek 2016-07-26 23:46:55 +03:00
parent 6f86c5092f
commit 573c062704
2 changed files with 11 additions and 15 deletions

View File

@ -425,10 +425,10 @@ func (d *Downsampling) Mean(fields ...Aggregation) (telegraf.Metric, error) {
var ( var (
aggrMetric telegraf.Metric aggrMetric telegraf.Metric
sums = make(map[string]interface{}) sums = make(map[string]interface{})
size = len(d.Metrics)
) )
d.RLock() d.RLock()
var size = len(d.Metrics)
for _, metric := range d.Metrics { for _, metric := range d.Metrics {
for _, field := range fields { for _, field := range fields {
value, ok := metric.Fields()[field.FieldName] value, ok := metric.Fields()[field.FieldName]

View File

@ -6,7 +6,7 @@ import (
"math/rand" "math/rand"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"sync" "sync/atomic"
"testing" "testing"
"time" "time"
@ -115,11 +115,9 @@ func TestDownsampling_aggregate(t *testing.T) {
} }
func TestDownsampling_run(t *testing.T) { func TestDownsampling_run(t *testing.T) {
testCase := struct { var (
sum int sum, count int32
count int )
sync.Mutex
}{}
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var createDatabaseQuery = "CREATE DATABASE IF NOT EXISTS \"\"" var createDatabaseQuery = "CREATE DATABASE IF NOT EXISTS \"\""
@ -151,11 +149,9 @@ func TestDownsampling_run(t *testing.T) {
return return
} }
testCase.Lock() want := atomic.LoadInt32(&sum) / atomic.LoadInt32(&count)
want := testCase.sum / testCase.count atomic.StoreInt32(&sum, 0)
testCase.sum = 0 atomic.StoreInt32(&count, 0)
testCase.count = 0
defer testCase.Unlock()
require.EqualValues(t, want, mean) require.EqualValues(t, want, mean)
@ -188,9 +184,9 @@ func TestDownsampling_run(t *testing.T) {
for { for {
select { select {
case <-tick: case <-tick:
testCase.count += 1 atomic.AddInt32(&count, 1)
val := rand.Intn(120) val := rand.Int31n(120)
testCase.sum += val atomic.AddInt32(&sum, val)
err := influxdb.Write([]telegraf.Metric{testutil.TestMetric(val)}) err := influxdb.Write([]telegraf.Metric{testutil.TestMetric(val)})
require.NoError(t, err) require.NoError(t, err)
case <-after: case <-after: