pkg/testutil: ForceGosched -> WaitSchedule

ForceGosched() performs bad when GOMAXPROCS>1. When GOMAXPROCS=1, it
could promise that other goroutines run long enough
because it always yield the processor to other goroutines. But it cannot
yield processor to goroutine running on other processors. So when
GOMAXPROCS>1, the yield may finish when goroutine on the other
processor just runs for little time.

Here is a test to confirm the case:

```
package main

import (
	"fmt"
	"runtime"
	"testing"
)

func ForceGosched() {
	// possibility enough to sched up to 10 go routines.
	for i := 0; i < 10000; i++ {
		runtime.Gosched()
	}
}

var d int

func loop(c chan struct{}) {
	for {
		select {
		case <-c:
			for i := 0; i < 1000; i++ {
				fmt.Sprintf("come to time %d", i)
			}
			d++
		}
	}
}

func TestLoop(t *testing.T) {
	c := make(chan struct{}, 1)
	go loop(c)
	c <- struct{}{}
	ForceGosched()
	if d != 1 {
		t.Fatal("d is not incremented")
	}
}
```

`go test -v -race` runs well, but `GOMAXPROCS=2 go test -v -race` fails.

Change the functionality to waiting for schedule to happen.
This commit is contained in:
Yicheng Qin
2015-06-09 19:26:23 -07:00
parent 05b55d9d75
commit 018fb8e6d9
6 changed files with 21 additions and 25 deletions

View File

@ -607,7 +607,7 @@ func TestSync(t *testing.T) {
})
srv.sync(10 * time.Second)
timer.Stop()
testutil.ForceGosched()
testutil.WaitSchedule()
action := n.Action()
if len(action) != 1 {
@ -642,7 +642,7 @@ func TestSyncTimeout(t *testing.T) {
timer.Stop()
// give time for goroutine in sync to cancel
testutil.ForceGosched()
testutil.WaitSchedule()
w := []testutil.Action{{Name: "Propose blocked"}}
if g := n.Action(); !reflect.DeepEqual(g, w) {
t.Errorf("action = %v, want %v", g, w)
@ -676,7 +676,7 @@ func TestSyncTrigger(t *testing.T) {
}
// trigger a sync request
st <- time.Time{}
testutil.ForceGosched()
testutil.WaitSchedule()
action := n.Action()
if len(action) != 1 {
@ -710,7 +710,7 @@ func TestSnapshot(t *testing.T) {
store: st,
}
srv.snapshot(1, raftpb.ConfState{Nodes: []uint64{1}})
testutil.ForceGosched()
testutil.WaitSchedule()
gaction := st.Action()
if len(gaction) != 2 {
t.Fatalf("len(action) = %d, want 1", len(gaction))
@ -786,7 +786,7 @@ func TestRecvSnapshot(t *testing.T) {
s.start()
n.readyc <- raft.Ready{Snapshot: raftpb.Snapshot{Metadata: raftpb.SnapshotMetadata{Index: 1}}}
// make goroutines move forward to receive snapshot
testutil.ForceGosched()
testutil.WaitSchedule()
s.Stop()
wactions := []testutil.Action{{Name: "Recovery"}}
@ -827,7 +827,7 @@ func TestApplySnapshotAndCommittedEntries(t *testing.T) {
},
}
// make goroutines move forward to receive snapshot
testutil.ForceGosched()
testutil.WaitSchedule()
s.Stop()
actions := st.Action()