forked from etcd-io/etcd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutex.go
72 lines (60 loc) · 1.03 KB
/
mutex.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 main
import (
"fmt"
"github.com/coreos/go-etcd/etcd"
)
var count = 0
func main() {
good := 0
bad := 0
ch := make(chan bool, 10)
// set up a lock
c := etcd.NewClient()
c.Set("lock", "unlock", 0)
for i := 0; i < 10; i++ {
go t(i, ch, etcd.NewClient())
}
for i := 0; i < 10; i++ {
if <-ch {
good++
} else {
bad++
}
}
fmt.Println("good: ", good, "bad: ", bad)
}
func t(num int, ch chan bool, c *etcd.Client) {
for i := 0; i < 100; i++ {
if lock(c) {
// a stupid spin lock
count++
fmt.Println(num, " got the lock and update count to", count)
unlock(c)
fmt.Println(num, " released the lock")
} else {
ch <- false
return
}
}
ch <- true
}
// A stupid spin lock
func lock(c *etcd.Client) bool {
for {
_, success, _ := c.TestAndSet("lock", "unlock", "lock", 0)
if success != true {
fmt.Println("tried lock failed!")
} else {
return true
}
}
}
func unlock(c *etcd.Client) {
for {
_, err := c.Set("lock", "unlock", 0)
if err == nil {
return
}
fmt.Println(err)
}
}