Skip to content

Commit

Permalink
expression: fix data race of rand function (#11168) (#11170)
Browse files Browse the repository at this point in the history
  • Loading branch information
alivxxx authored and zz-jason committed Jul 11, 2019
1 parent 79eba3c commit 7cdce5b
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
13 changes: 9 additions & 4 deletions expression/builtin_math.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"math/rand"
"strconv"
"strings"
"sync"
"time"

"github.com/cznic/mathutil"
Expand Down Expand Up @@ -967,7 +968,7 @@ func (c *randFunctionClass) getFunction(ctx sessionctx.Context, args []Expressio
bt := bf
if len(args) == 0 {
seed := time.Now().UnixNano()
sig = &builtinRandSig{bt, rand.New(rand.NewSource(seed))}
sig = &builtinRandSig{bt, &sync.Mutex{}, rand.New(rand.NewSource(seed))}
} else if _, isConstant := args[0].(*Constant); isConstant {
// According to MySQL manual:
// If an integer argument N is specified, it is used as the seed value:
Expand All @@ -980,7 +981,7 @@ func (c *randFunctionClass) getFunction(ctx sessionctx.Context, args []Expressio
if isNull {
seed = time.Now().UnixNano()
}
sig = &builtinRandSig{bt, rand.New(rand.NewSource(seed))}
sig = &builtinRandSig{bt, &sync.Mutex{}, rand.New(rand.NewSource(seed))}
} else {
sig = &builtinRandWithSeedSig{bt}
}
Expand All @@ -989,19 +990,23 @@ func (c *randFunctionClass) getFunction(ctx sessionctx.Context, args []Expressio

type builtinRandSig struct {
baseBuiltinFunc
mu *sync.Mutex
randGen *rand.Rand
}

func (b *builtinRandSig) Clone() builtinFunc {
newSig := &builtinRandSig{randGen: b.randGen}
newSig := &builtinRandSig{randGen: b.randGen, mu: b.mu}
newSig.cloneFrom(&b.baseBuiltinFunc)
return newSig
}

// evalReal evals RAND().
// See https://dev.mysql.com/doc/refman/5.7/en/mathematical-functions.html#function_rand
func (b *builtinRandSig) evalReal(row chunk.Row) (float64, bool, error) {
return b.randGen.Float64(), false, nil
b.mu.Lock()
res := b.randGen.Float64()
b.mu.Unlock()
return res, false, nil
}

type builtinRandWithSeedSig struct {
Expand Down
2 changes: 2 additions & 0 deletions expression/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,8 @@ func (s *testIntegrationSuite) TestMathBuiltin(c *C) {
tk.MustExec("drop table if exists t")
tk.MustExec("create table t(a int)")
tk.MustExec("insert into t values(1),(2),(3)")
tk.Se.GetSessionVars().MaxChunkSize = 1
tk.MustQuery("select rand(1) from t").Sort().Check(testkit.Rows("0.6046602879796196", "0.6645600532184904", "0.9405090880450124"))
tk.MustQuery("select rand(a) from t").Check(testkit.Rows("0.6046602879796196", "0.16729663442585624", "0.7199826688373036"))
tk.MustQuery("select rand(1), rand(2), rand(3)").Check(testkit.Rows("0.6046602879796196 0.16729663442585624 0.7199826688373036"))
}
Expand Down

0 comments on commit 7cdce5b

Please sign in to comment.