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
|
package main
import (
"sync"
)
// Lock 锁结构
type Lock struct {
c chan struct{}
}
// NewLock 生成一个锁
func NewLock() Lock {
var l Lock
l.c = make(chan struct{}, 1)
l.c <- struct{}{} // 放入一把锁用于获取
return l
}
// TryLock 尝试加锁,成功返回true,失败返回false,不会阻塞等待
func (l Lock) TryLock() bool {
var lockResult bool
select {
case <-l.c:
lockResult = true
default:
}
return lockResult
}
// 加锁,会阻塞竞争
func (l Lock) Lock() {
<-l.c
}
// 解锁,重复解锁会阻塞
func (l Lock) Unlock() {
l.c <- struct{}{}
}
var counter int
func main() {
l := NewLock()
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if !l.TryLock() {
println("lock failed")
return
}
counter++
println("try lock counter ", counter)
l.Unlock()
}()
}
for i := 0; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
l.Lock()
counter++
println("lock counter ", counter)
l.Unlock()
}()
}
wg.Wait()
}
|