-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex_windows_test.go
100 lines (84 loc) · 1.54 KB
/
mutex_windows_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package mutex
import (
"errors"
"sync"
"testing"
"time"
)
func ExampleAcquire() {
r, err := Acquire("kvii_mutex_example_acquire")
if err != nil {
panic(err)
}
defer r.Release()
if r.IsAbandoned() {
// 检查被加锁的资源是否处于一致状态
}
// Output:
}
func ExampleAcquireWithTimeout() {
r, err := AcquireWithTimeout("kvii_mutex_example_acquire_with_timeout", time.Second)
if err != nil {
panic(err)
}
defer r.Release()
if r.IsAbandoned() {
// 检查被加锁的资源是否处于一致状态
}
// Output:
}
func TestAcquire(t *testing.T) {
const name = "kvii_mutex_test_acquire"
var wg sync.WaitGroup
var err error
var once sync.Once
var i int
wg.Add(1)
go func() {
defer wg.Done()
r, e := Acquire(name)
if e != nil {
once.Do(func() { err = e })
}
defer r.Release()
if r.IsAbandoned() {
t.Log("abandoned")
}
i++
}()
wg.Add(1)
go func() {
defer wg.Done()
r, e := Acquire(name)
if e != nil {
once.Do(func() { err = e })
}
defer r.Release()
if r.IsAbandoned() {
t.Log("abandoned")
}
i++
}()
wg.Wait()
if err != nil {
t.Fatal(err)
}
if i != 2 {
t.Fatalf("expect 2, got %d", i)
}
}
func TestAcquireWithTimeout(t *testing.T) {
const name = "kvii_mutex_test_acquire_with_timeout"
r1, err := Acquire(name)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = r1.Release() })
r2, err := AcquireWithTimeout(name, time.Second)
if !errors.Is(err, ErrWaitTimeout) {
if err == nil {
_ = r2.Release()
}
t.Fatalf("expect ErrWaitTimeout, got %v", err)
}
}