How do I check if a goroutine is created successfully?

Issue

In Go, go is the keyword to spawn a goroutine. However, it seems the keyword doesn’t return any value, so how could I detect if the goroutine is spawned correctly?

It seems Go uses the following ways to check whether a func is successful or not.

value, err = myFunc(value)

Is there a similar usage for the go keyword to detect a creation error? It seems go will throw a runtime exception if it failed.

I want to make a test to find out the maximum number of goroutine I could create for a CPU.

Solution

As you already know:

value, err = myFunc(value)

is the idiomatic way to handle exceptions by returning the built-in error type. In a way you can compare it to a checked exception, I guess. In your case though, failing to spawn a new goroutine is more of a runtime exception. How golang handles those is by using panics. You can handle them in your code with the built-in recover() function, which will try to regain control of the execution flow. Without that the panic will go up the stack until it crashes the program.

Notice that recover() has to be called in a function which is being defered, those functions are pushed into a list and are always called at the end of the function in which they were defered – so even when the panic occurs they will be called, allowing you to call recover(). If you just try to call recover() at the end of your function (or well anywhere after you panicking subfunction) the execution will never reach it. If you can handle the panic (recover() doesn’t return an err) so that your program can actually continue it will execute from the point where the function that threw the panic was.

Think the above blog post is enough but if you need more examples just comment here.

Also your system will most probably be bounded by RAM memory rather than CPU.

Answered By – Mateusz Dymczyk

Answer Checked By – Marilyn (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.