Simple goroutine not working on Windows

痴心易碎 提交于 2020-08-19 06:29:09

问题


I'm doing some tests with goroutines just to learn how they work, however it seems they are not running at all. I've done a very simple test:

package main

import (
    "fmt"
)

func test() {
    fmt.Println("test")
}

func main() {
    go test()
}

I would expect this to print "test" however it simply doesn't do anything, no message but no error either. I've also tried adding a for {} at the end of the program to give the goroutine time to print something but that didn't help.

Any idea what could be the issue?


回答1:


program execution does not wait for the invoked function to complete

Go statements

Wait a while. For example,

package main

import (
    "fmt"
    "time"
)

func test() {
    fmt.Println("test")
}

func main() {
    go test()
    time.Sleep(10 * time.Second)
}

Output:

test



回答2:


I know it's answered, but for the sake of completeness:

Channels

package main

import (
    "fmt"
)

func test(c chan int) {
    fmt.Println("test")

    // We are done here.
    c <- 1
}

func main() {
    c := make(chan int)
    go test(c)

    // Wait for signal on channel c
    <- c
}


来源:https://stackoverflow.com/questions/14664545/simple-goroutine-not-working-on-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!