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.

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

报告相同问题?

悬赏问题

  • ¥20 关于#深度学习#的问题:2708)输出:邻接矩阵A 或者 节点索引方式:通过随机游走或者其他方式,保持节点连接类似下图(语言-python)
  • ¥15 win2012 iscsi ipsec
  • ¥15 封装的 matplotlib animation 不显示图像
  • ¥15 python摄像头画面无法显示
  • ¥15 关于#3d#的问题:d标定算法(语言-python)
  • ¥15 cve,cnnvd漏洞扫描工具推荐
  • ¥15 图像超分real-esrgan网络自己训练模型遇到问题
  • ¥15 如何构建全国统一的物流管理平台?
  • ¥100 ijkplayer使用AndroidStudio/CMake编译,如何支持 rtsp 直播流?
  • ¥15 用js遍历数据并对非空元素添加css样式