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.

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

报告相同问题?

悬赏问题

  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding