如何检查goroutine是否成功创建?

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.

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.

A goroutine creation is (more or less) just a memory allocation. You cannot in general catch memory allocation exceptions and it's the same with goroutines.

If your program runs out of memory, there's usually nothing you can do about it beyond quitting and restarting.

If the function you are using a go routine that returns an error, you can instead call go on an anonymous function and handle the error in the anonymous function.

go func() {
    value, err := myFunc()
}()