dpjpo746884 2015-07-02 08:37
浏览 29
已采纳

为什么不处理“无限” for循环?

I need to wait until x.Addr is being updated but it seems the for loop is not run. I suspect this is due the go scheduler and I'm wondering why it works this way or if there is any way I can fix it(without channels).

package main

import "fmt"
import "time"

type T struct {
    Addr *string
}

func main() {

    x := &T{}
    go update(x)
    for x.Addr == nil {
        if x.Addr != nil {
            break
        }
    }
    fmt.Println("Hello, playground")
}

func update(x *T) {
    time.Sleep(2 * time.Second)
    y := ""
    x.Addr = &y
}
  • 写回答

1条回答 默认 最新

  • dongmo3413 2015-07-02 08:48
    关注

    There are two (three) problems with your code.

    First, you are right that there is no point in the loop at which you give control to the scheduler and such it can't execute the update goroutine. To fix this you can set GOMAXPROCS to something bigger than one and then multiple goroutines can run in parallel.

    (However, as it is this won't help as you pass x by value to the update function which means that the main goroutine will never see the update on x. To fix this problem you have to pass x by pointer. Now obsolete as OP fixed the code.)

    Finally, note that you have a data race on Addr as you are not using atomic loads and stores.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 三相直流充电模块对数字电源芯片在物理上它必须具备哪些功能和性能?
  • ¥30 数字电源对DSP芯片的具体要求
  • ¥20 antv g6 折线边如何变为钝角
  • ¥30 如何在Matlab或Python中 设置饼图的高度
  • ¥15 nginx中的CORS策略应该如何配置
  • ¥30 信号与系统实验:采样定理分析
  • ¥100 我想找人帮我写Python 的股票分析代码,有意请加mathtao
  • ¥20 Vite 打包的 Vue3 组件库,图标无法显示
  • ¥15 php 同步电商平台多个店铺增量订单和订单状态
  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别