-
Notifications
You must be signed in to change notification settings - Fork 0
/
trymutex_test.go
84 lines (66 loc) · 1.55 KB
/
trymutex_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
package gosync_test
import (
"fmt"
"testing"
"time"
"github.com/thecodeteam/gosync"
)
func TestTryMutex_PanicOnUnlockOfUnlockedMutex(t *testing.T) {
defer func() {
e := recover()
if e != "gosync: unlock of unlocked mutex" {
panic(e)
}
}()
var m gosync.TryMutex
m.Unlock()
}
func TestTryMutex_Lock(t *testing.T) {
var (
i int
m gosync.TryMutex
)
// Start five goroutines that all attempt to lock m and increment i.
for j := 0; j < 5; j++ {
go func() {
m.Lock()
i++
}()
}
// Give the above loop enough time to start the goroutines.
time.Sleep(time.Duration(3) * time.Second)
// Assert that i should have only been incremented once since only
// one lock should have been obtained.
if i != 1 {
t.Fatalf("i != 1: %d", i)
}
// Unlock the mutex without panic.
m.Unlock()
}
func ExampleTryMutex_TryLock() {
// Assign a gosync.TryMutex to m and then lock it
var m gosync.TryMutex
m.Lock()
// Start a goroutine that sleeps for one second and then
// unlocks m. This makes it possible for the above TryLock
// call to lock m.
go func() {
time.Sleep(time.Duration(1) * time.Second)
m.Unlock()
}()
// Try for three seconds to lock m.
if m.TryLock(time.Duration(3) * time.Second) {
fmt.Println("lock obtained")
}
// Output: lock obtained
}
func ExampleTryMutex_TryLock_timeout() {
// Assign a gosync.TryMutex to m and then lock m.
var m gosync.TryMutex
m.Lock()
// Try for three seconds to lock m.
if !m.TryLock(time.Duration(3) * time.Second) {
fmt.Println("lock not obtained")
}
// Output: lock not obtained
}