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 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题