### 测试使用的操作系统及内核版本
```shell
$ uname -a
Linux CentOS 3.10.0-1127.8.2.el7.x86_64 #1 SMP Tue May 12 16:57:42 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
```
### 使用sync.Mutex实现锁机制代码
```go
package main
import "sync"
func main() {
num, wg, mux := new(int), new(sync.WaitGroup), new(sync.Mutex)
wg.Add(2)
go func(num *int, wg *sync.WaitGroup, mux *sync.Mutex) {
defer wg.Done()
for i := 1; i <= 100000000; i++ {
mux.Lock()
*num++
mux.Unlock()
}
}(num, wg, mux)
go func(num *int, wg *sync.WaitGroup, mux *sync.Mutex) {
defer wg.Done()
for i := 1; i <= 100000000; i++ {
mux.Lock()
*num--
mux.Unlock()
}
}(num, wg, mux)
wg.Wait()
println(*num)
}
```
### 操作系统执行时间
```shell
$ time ./test-mutex
0
real 0m8.638s
user 0m16.980s
sys 0m0.012s
```
### 使用chan bool实现锁机制代码
```go
package main
import "sync"
func main() {
num, wg, mux := new(int), new(sync.WaitGroup), make(chan bool, 1)
defer close(mux)
wg.Add(2)
go func(num *int, wg *sync.WaitGroup, mux chan bool) {
defer wg.Done()
for i := 1; i <= 100000000; i++ {
mux <- true
*num++
<-mux
}
}(num, wg, mux)
go func(num *int, wg *sync.WaitGroup, mux chan bool) {
defer wg.Done()
for i := 1; i <= 100000000; i++ {
mux <- true
*num--
<-mux
}
}(num, wg, mux)
wg.Wait()
println(*num)
}
```
### 操作系统执行时间
```shell
$ time ./test-chan
0
real 0m44.766s
user 0m48.069s
sys 0m1.276s
```
在golang中实现锁机制可以完全不需要考虑通道了,因为性能开销实在不是一个数量级
有疑问加站长微信联系(非本文作者))