Why is the loop "infinite" for the loop not processed?

I need to wait for x.Addr to update, but it seems the for loop is not starting. I suspect this is due to the go scheduler, and I wonder why it works this way, or if 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
}
+4
source share
1 answer

There are two (three) problems in the code.

Firstly, you are right that there is no point in the loop at which you give the scheduler control, and therefore it cannot update the goroutine. To fix this, you can install GOMAXPROCSon something more than one, and then several parallel routes can run in parallel.

( , , x , , goroutine x. , x . , OP, .)

, , Addr, .

+3

All Articles