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.

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

报告相同问题?