-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmutex_test.go
72 lines (68 loc) · 1.3 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
package sync
import (
"context"
"fmt"
"testing"
"time"
"github.com/go-redis/redis/v8"
)
func TestRedisMutex(t *testing.T) {
var ctx = context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := rdb.Ping(ctx).Result()
if err != nil {
t.Error(err)
return
}
t.Log(pong)
rs := NewRedisSync(rdb)
m := rs.NewMutex("test_key")
m.Lock()
for i := 0; i < 10; i++ {
err = m.Lock()
fmt.Println("lock:", err)
time.Sleep(time.Second * 2)
if i%2 == 0 {
fmt.Println("2的倍数解锁")
err = m.Unlock()
if err != nil {
fmt.Println("unlock:", err)
}
}
}
err = m.Unlock()
if err != nil {
fmt.Println("unlock:", err)
}
}
func BenchmarkRedisMutex(b *testing.B) {
var ctx = context.Background()
rdb := redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "", // no password set
DB: 0, // use default DB
})
pong, err := rdb.Ping(ctx).Result()
if err != nil {
b.Error(err)
return
}
b.Log(pong)
rs := NewRedisSync(rdb)
b.ResetTimer()
m := rs.NewMutex("test_benchmark")
for i := 0; i < b.N; i++ {
err = m.Lock()
if err != nil {
b.Errorf("Lock: %s", err)
}
err = m.Unlock()
if err != nil {
b.Errorf("Unlock: %s", err)
}
}
}