简单的goroutine在Windows上无法工作

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

Simple goroutine not working on Windows

问题

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

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func test() {
  6. fmt.Println("test")
  7. }
  8. func main() {
  9. go test()
  10. }

我期望这个程序会打印出"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:

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func test() {
  6. fmt.Println("test")
  7. }
  8. func main() {
  9. go test()
  10. }

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

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

等一会儿。例如,

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func test() {
  7. fmt.Println("test")
  8. }
  9. func main() {
  10. go test()
  11. time.Sleep(10 * time.Second)
  12. }

输出:

  1. test
英文:

> program execution does not wait for the invoked function to complete
>
> Go statements

Wait a while. For example,

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func test() {
  7. fmt.Println("test")
  8. }
  9. func main() {
  10. go test()
  11. time.Sleep(10 * time.Second)
  12. }

Output:

  1. test

答案2

得分: 10

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

通道

  1. package main
  2. import (
  3. "fmt"
  4. )
  5. func test(c chan int) {
  6. fmt.Println("test")
  7. // 我们在这里完成了。
  8. c <- 1
  9. }
  10. func main() {
  11. c := make(chan int)
  12. go test(c)
  13. // 等待通道 c 上的信号
  14. <- c
  15. }
英文:

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

Channels

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. )
  5. func test(c chan int) {
  6. fmt.Println(&quot;test&quot;)
  7. // We are done here.
  8. c &lt;- 1
  9. }
  10. func main() {
  11. c := make(chan int)
  12. go test(c)
  13. // Wait for signal on channel c
  14. &lt;- c
  15. }

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:

确定