简单的goroutine在Windows上无法工作

huangapple go评论88阅读模式
英文:

Simple goroutine not working on Windows

问题

我正在进行一些关于goroutine的测试,只是为了学习它们的工作原理,然而它们似乎根本没有运行。我做了一个非常简单的测试:

package main

import (
	"fmt"
)

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

func main() {
	go test()
}

我期望这个程序会打印出"test",然而它什么都不做,既没有消息也没有错误。我还尝试在程序的末尾添加了一个for {},以便给goroutine一些时间来打印一些东西,但是这并没有帮助。

有什么想法可能是问题所在?

英文:

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

得分: 11

程序执行不会等待被调用的函数完成。

等一会儿。例如,

package main

import (
	"fmt"
	"time"
)

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

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

输出:

test
英文:

> 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

得分: 10

我知道这个问题已经有答案了,但为了完整起见:

通道

package main

import (
    "fmt"
)

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

    // 我们在这里完成了。
    c <- 1
}

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

    // 等待通道 c 上的信号
    <- c
}
英文:

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

Channels

package main

import (
    &quot;fmt&quot;
)

func test(c chan int) {
    fmt.Println(&quot;test&quot;)

    // We are done here.
    c &lt;- 1
}

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

    // Wait for signal on channel c
    &lt;- c
}

huangapple
  • 本文由 发表于 2013年2月3日 01:35:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/14664545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定