dongqinta4174 2014-04-08 05:52
浏览 54
已采纳

为什么在此golang代码段中,指向WaitGroup的指针的地址不同?

Code snippet on playground

I am printing the pointer address for sync.WaitGroup and they are all different. Why?

func Run() *sync.WaitGroup {
    var wg sync.WaitGroup
    wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Printf("goroutine %p
", &wg)

        time.Sleep(5 * time.Second)
        fmt.Println("wokeup")
    }()

    fmt.Printf("returning %p
", &wg)
    return &wg
}

func main() {
    runtime.GOMAXPROCS(3)
    wg := Run()

    fmt.Printf("     main %p
", &wg)
    wg.Wait()
}

Typical output shows that the address is diff between that inside the function Run and main. I'd expect that to be the same, n'est-ce pas ?

returning 0xc0840045c0
     main 0xc084000038
goroutine 0xc0840045c0
wokeup
  • 写回答

2条回答 默认 最新

  • doukenqiong0588 2014-04-08 06:43
    关注

    For example,

    package main
    
    import "fmt"
    import "sync"
    import "time"
    import "runtime"
    
    func Run() *sync.WaitGroup {
        var wg sync.WaitGroup
        wg.Add(1)
        go func() {
            defer wg.Done()
            fmt.Printf("goroutine %p
    ", &wg)
            fmt.Println("sleep for 5s")
            time.Sleep(5 * time.Second)
            fmt.Println("wokeup")
        }()
        fmt.Printf("returning %p
    ", &wg)
        return &wg
    }
    
    func main() {
        runtime.GOMAXPROCS(3)
        wg := Run()
        fmt.Printf("     main %p
    ", wg)
        wg.Wait()
    }
    

    Output:

    returning 0x1052e2c0
         main 0x1052e2c0
    goroutine 0x1052e2c0
    sleep for 5s
    

    Change

    fmt.Printf("     main %p
    ", &wg)
    

    to

    fmt.Printf("     main %p
    ", wg)
    

    In main, the variable wg contains the address you want. You are printing the address of the variable that contains the address.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 yolov8边框坐标
  • ¥15 matlab中使用gurobi时报错
  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真