mirror of
https://github.com/ethereum/go-ethereum.git
synced 2026-08-18 18:02:24 +00:00
internal/syncx: make a proper test
This commit is contained in:
parent
6d9909e7e8
commit
471533a209
1 changed files with 20 additions and 14 deletions
|
|
@ -2,33 +2,39 @@ package syncx
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCancel(t *testing.T) {
|
func TestTryWithContext(t *testing.T) {
|
||||||
t.Skip("not a good test, also time-consuming")
|
|
||||||
mu := NewClosableMutex()
|
mu := NewClosableMutex()
|
||||||
var wg sync.WaitGroup
|
var wg sync.WaitGroup
|
||||||
wg.Add(3)
|
res := []bool{false, false}
|
||||||
waiter := func(id int, waitTime time.Duration) {
|
waiter := func(id int, waitTime time.Duration) {
|
||||||
defer wg.Done()
|
defer wg.Done()
|
||||||
ctx, _ := context.WithTimeout(context.Background(), waitTime)
|
ctx, _ := context.WithTimeout(context.Background(), waitTime)
|
||||||
if mu.TryLockWithContext(ctx) {
|
if mu.TryLockWithContext(ctx) {
|
||||||
fmt.Printf("%d. Sleeping\n", id)
|
|
||||||
time.Sleep(10 * time.Second)
|
|
||||||
fmt.Printf("%d. Waking\n", id)
|
|
||||||
mu.Unlock()
|
mu.Unlock()
|
||||||
} else {
|
res[id] = true
|
||||||
fmt.Printf("%d. Cancelling\n", id)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Obtain the lock
|
||||||
go waiter(1, 5*time.Second)
|
if !mu.TryLock() {
|
||||||
time.Sleep(100 * time.Millisecond)
|
t.Fatalf("lock failed")
|
||||||
go waiter(2, 5*time.Second)
|
}
|
||||||
go waiter(3, 15*time.Second)
|
// Launch goroutines
|
||||||
|
wg.Add(2)
|
||||||
|
go waiter(0, 100*time.Millisecond) // This one should cancel
|
||||||
|
go waiter(1, 5*time.Second) // This one should make it
|
||||||
|
// Sleep for a bit.
|
||||||
|
time.Sleep(1 * time.Second)
|
||||||
|
mu.Unlock()
|
||||||
wg.Wait()
|
wg.Wait()
|
||||||
|
if have, want := res[0], false; have != want {
|
||||||
|
t.Fatalf("have %v want %v", have, want)
|
||||||
|
}
|
||||||
|
if have, want := res[1], true; have != want {
|
||||||
|
t.Fatalf("have %v want %v", have, want)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue