英文:
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 (
"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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论