Skip to content

Commit

Permalink
expression: make sleep function response to the kill stateme… (#11028)
Browse files Browse the repository at this point in the history
  • Loading branch information
tiancaiamao authored and zz-jason committed Jul 3, 2019
1 parent 2e406b0 commit 0d7ac5f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 21 deletions.
22 changes: 18 additions & 4 deletions expression/builtin_miscellaneous.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
"math"
"net"
"strings"
"sync/atomic"
"time"

"github.com/google/uuid"
Expand Down Expand Up @@ -131,12 +132,25 @@ func (b *builtinSleepSig) evalInt(row chunk.Row) (int64, bool, error) {
if val > math.MaxFloat64/float64(time.Second.Nanoseconds()) {
return 0, false, errIncorrectArgs.GenWithStackByArgs("sleep")
}

dur := time.Duration(val * float64(time.Second.Nanoseconds()))
select {
case <-time.After(dur):
// TODO: Handle Ctrl-C is pressed in `mysql` client.
// return 1 when SLEEP() is KILLed
ticker := time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
start := time.Now()
finish := false
for !finish {
select {
case now := <-ticker.C:
if now.Sub(start) > dur {
finish = true
}
default:
if atomic.CompareAndSwapUint32(&sessVars.Killed, 1, 0) {
return 1, false, nil
}
}
}

return 0, false, nil
}

Expand Down
33 changes: 16 additions & 17 deletions expression/evaluator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
package expression

import (
"sync/atomic"
"testing"
"time"

Expand Down Expand Up @@ -176,23 +177,21 @@ func (s *testEvaluatorSuite) TestSleep(c *C) {
sub := time.Since(start)
c.Assert(sub.Nanoseconds(), GreaterEqual, int64(0.5*1e9))

// quit when context canceled.
// TODO: recover it.
// d[0].SetFloat64(2)
// f, err = fc.getFunction(ctx, s.datumsToConstants(d))
// c.Assert(err, IsNil)
// start = time.Now()
// go func() {
// time.Sleep(1 * time.Second)
// ctx.Cancel()
// }()
// ret, isNull, err = f.evalInt(chunk.Row{})
// sub = time.Since(start)
// c.Assert(err, IsNil)
// c.Assert(isNull, IsFalse)
// c.Assert(ret, Equals, int64(1))
// c.Assert(sub.Nanoseconds(), LessEqual, int64(2*1e9))
// c.Assert(sub.Nanoseconds(), GreaterEqual, int64(1*1e9))
d[0].SetFloat64(3)
f, err = fc.getFunction(ctx, s.datumsToConstants(d))
c.Assert(err, IsNil)
start = time.Now()
go func() {
time.Sleep(1 * time.Second)
atomic.CompareAndSwapUint32(&ctx.GetSessionVars().Killed, 0, 1)
}()
ret, isNull, err = f.evalInt(chunk.Row{})
sub = time.Since(start)
c.Assert(err, IsNil)
c.Assert(isNull, IsFalse)
c.Assert(ret, Equals, int64(1))
c.Assert(sub.Nanoseconds(), LessEqual, int64(2*1e9))
c.Assert(sub.Nanoseconds(), GreaterEqual, int64(1*1e9))
}

func (s *testEvaluatorSuite) TestBinopComparison(c *C) {
Expand Down

0 comments on commit 0d7ac5f

Please sign in to comment.