package main
import (
"fmt"
"sync"
)
var a = 1
func main() {
lock := sync.Mutex{}
wg := &sync.WaitGroup{}
wg.Add(2)
go t(lock,wg)
go t(lock,wg)
wg.Wait()
fmt.Println(a)
}
func t(lock sync.Mutex, wg *sync.WaitGroup){
defer wg.Done()
lock.Lock()
defer lock.Unlock()
for i:=0;i<10000000;i++{
a++
}
}
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
输出
11380825
修正
代码
package main
import (
"fmt"
"sync"
)
var a = 1
func main() {
lock := &sync.Mutex{}
wg := &sync.WaitGroup{} // 改成指针
wg.Add(2)
go t(lock,wg)
go t(lock,wg)
wg.Wait()
fmt.Println(a)
}
func t(lock *sync.Mutex, wg *sync.WaitGroup){ // 改成指针
defer wg.Done()
lock.Lock()
defer lock.Unlock()
for i:=0;i<10000000;i++{
a++
}
}
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
结果
20000001
这才是正确的结果
结论
函数参数传递sync.Mutex一定要是指针
————————————————
版权声明:本文为CSDN博主「cumt_TTR」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/cumt_TTR/article/details/112387024