-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutex_test.go
79 lines (69 loc) · 1.54 KB
/
mutex_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
package scope_test
import (
"fmt"
"sync"
"github.com/goaux/scope"
)
func ExampleLock() {
var mu sync.Mutex
for range scope.Lock(&mu) {
// mu is locked.
fmt.Println("pass 0")
}
fmt.Println("pass 1")
// Output:
// pass 0
// pass 1
}
func ExampleLock_rWMutex() {
var mu sync.RWMutex
for range scope.Lock(&mu) {
// mu is locked for writing.
fmt.Println("pass 0")
// mu will be unlocked at the end of the loop body.
}
fmt.Println("pass 1")
for range scope.Lock(mu.RLocker()) {
// mu is locked for reading.
fmt.Println("pass 2")
}
fmt.Println("pass 3")
// Output:
// pass 0
// pass 1
// pass 2
// pass 3
}
func ExampleLock_inspect() {
var mu TestLocker
for range scope.Lock(&mu) {
// mu is locked for writing.
fmt.Println("pass 0")
// mu will be unlocked at the end of the loop body.
}
fmt.Println("pass 1")
for range scope.Lock(mu.RLocker()) {
// mu is locked for reading.
fmt.Println("pass 2")
// mu will be unlocked at the end of the loop body.
}
fmt.Println("pass 3")
// Output:
// Lock
// pass 0
// Unlock
// pass 1
// RLock
// pass 2
// RUnlock
// pass 3
}
type TestLocker struct{}
func (*TestLocker) Lock() { fmt.Println("Lock") }
func (*TestLocker) Unlock() { fmt.Println("Unlock") }
func (*TestLocker) RLock() { fmt.Println("RLock") }
func (*TestLocker) RUnlock() { fmt.Println("RUnlock") }
func (*TestLocker) RLocker() sync.Locker { return (*rlocker)(nil) }
type rlocker TestLocker
func (r *rlocker) Lock() { (*TestLocker)(r).RLock() }
func (r *rlocker) Unlock() { (*TestLocker)(r).RUnlock() }