Is it possible to fail when executing go f
?
Since the keyword go has no return value, how to determine whether a goroutine is successfully started during high concurrency?
For Example:
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg = &sync.WaitGroup{}
go func() { // How do I know if there is any failure here?
wg.Add(1)
fmt.Println("halo world")
wg.Done()
}()
time.Sleep(time.Nanosecond)
wg.Wait()
}
The go
statement cannot fail (only in "extreme" circumstances like out of memory, but then a failing go
statement would be the least of your problems).
Of course without synchronization you don't have guarantee when that goroutine is scheduled to run. Your example use of sync.WaitGroup
therefore is incorrect, as if the goroutine is not scheduled until the main
goroutine reaches wg.Wait()
, it may never even start, as when the main
goroutine ends, your program ends as well.
Instead increment the WaitGroup's counter in the main goroutine (and it's best to call WaitGroup.Done()
deferred, so it gets called even if the goroutine would panic):
var wg = &sync.WaitGroup{}
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("halo world")
}()
wg.Wait()
That way you don't even need the sleep, wg.Wait()
will block until the other goroutine calls wg.Done()
(which will happen only when the other goroutine completed its work).