golang[88]-互斥锁与通道锁哪个更快

下面的程序来证明,极端情况下,互斥锁要比通道锁更快。

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
package main

import (
"sync"
"testing"
"time"
)


type center struct {
workers []*worker
ch chan struct{}
ch2 chan struct{}
sema chan struct{}
}

type worker struct {
sync.Mutex
count int64
}

func init(){
c.ch = make(chan struct{},10)
c.ch2 = make(chan struct{},10)
c.sema = make(chan struct{},1)
for i:=0;i<4;i++{
w:= new(worker)
c.workers = append(c.workers,w)
go w.do()
go w.do2()
}
}

func(w *worker) do(){
for {
select {
case <-c.ch:
w.Lock()
time.Sleep(1*time.Millisecond)
w.Unlock()
}
}
}

func(w *worker) do2(){
for {
select {
case <-c.ch2:
c.sema<- struct{}{}
time.Sleep(1*time.Millisecond)
<-c.sema
}
}
}

var c center
func Benchmark1(b *testing.B) {
for i := 0; i < b.N; i++ {
c.ch<- struct{}{}
}
}

func Benchmark2(b *testing.B) {
for i := 0; i < b.N; i++ {
c.ch2<- struct{}{}
}
}