Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple goroutine not working on Windows

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?

like image 956
laurent Avatar asked Feb 02 '13 17:02

laurent


People also ask

How do you know if a Goroutine is running?

The best way is not to know if it's till alive but to know when it dies so you can restart it. You can do that by setting a defer with a recover on your goroutine which would write to a channel signaling the death of the goroutine.

How do I call Goroutine?

To invoke this function in a goroutine, use go f(s) . This new goroutine will execute concurrently with the calling one. You can also start a goroutine for an anonymous function call. Our two function calls are running asynchronously in separate goroutines now.

Can Goroutines run in parallel?

The diagram shows that by using goroutines, your concurrent program is capable of running on a single CPU core, but as more CPU cores are added, more goroutines can be run in parallel to speed up the program.

How is Goroutine implemented?

Implementation. Goroutines are lightweight, costing little more than the allocation of stack space. The stacks start small and grow by allocating and freeing heap storage as required. Internally goroutines act like coroutines that are multiplexed among multiple operating system threads.


2 Answers

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
like image 60
peterSO Avatar answered Oct 08 '22 05:10

peterSO


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
}
like image 32
Kiril Avatar answered Oct 08 '22 04:10

Kiril