Goroutine执行几秒钟但停止[重复]

I'm currently learning golang and I've tried the following code:

package main

import (
    "fmt"
)

func main() {
    go routine()
    go routine2()

    fmt.Println("I am not interrupted by Go routine :)")

    for {

    }
}

func routine() {
    for {
        fmt.Println("hello, world!")
    }
}

func routine2() {
    for {
        fmt.Println("hello, world222")
    }
}

When I run this program, I get as output: "hello, world" and "hello, world222" for a few seconds. However, after a few seconds, I don't get anything anymore however the program is still running.

What's wrong? Why does the program stop displaying hello, world and hello, world222 ?

</div>

This is because for now (go 1.10) Go's scheduler is not preemptive, and there is no plans to make it so.

What this means is that Go's scheduler can stuck in some rare cases, where that there is an infinte loop doing nothing Go's schedule feels like to interupt. And that includes an empty infinite loop.

To block the goroutine for test, use select{} instead of for {}.

References:

https://github.com/golang/go/issues/11462

https://github.com/golang/go/issues/10958

You are burning CPU with the empty for loop Use select instead for

import (
    "fmt"
    "time"
)

func main() {
    go routine()
    go routine2()

    fmt.Println("I am not interrupted by Go routine :)")
    select{}
}

func routine() {
    for {
        fmt.Println("hello, world!")
        time.Sleep(time.Second)
    }
}

func routine2() {
    for {
        fmt.Println("hello, world222")
        time.Sleep(time.Second)
    }
}

Your code is okay, never stops but it's correct.