zoukankan      html  css  js  c++  java
  • golang,函数参数传递的sync.Mutex不是指针会怎么样

    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

  • 相关阅读:
    Python assert(断言)
    Python importlib(动态导入模块)
    Python 异常处理
    Qt Clipboard剪贴板简单使用
    Qt5 QTableWidget设置列表自动适应列宽
    Fix VNC Desktop Sharing on Ubuntu Desktop 14.04
    Golang 交叉编译
    stdobj to array php
    Elasticsearch-集群原理
    Elasticsearch-基本操作2
  • 原文地址:https://www.cnblogs.com/ExMan/p/15246258.html
Copyright © 2011-2022 走看看