go - What's wrong with this golang code? -
while sayhello()
executes expected, goroutine prints nothing.
package main import "fmt" func sayhello() { := 0; < 10 ; i++ { fmt.print(i, " ") } } func main() { sayhello() go sayhello() }
when main()
function ends, program ends well. not wait other goroutines finish.
quoting go language specification: program execution:
program execution begins initializing main package , invoking function
main
. when function invocation returns, program exits. not wait other (non-main
) goroutines complete.
see this answer more details.
you have tell main()
function wait sayhello()
function started goroutine complete. can synchronize them channels example:
func sayhello(done chan int) { := 0; < 10; i++ { fmt.print(i, " ") } if done != nil { done <- 0 // signal we're done } } func main() { sayhello(nil) // passing nil: don't want notification here done := make(chan int) go sayhello(done) <-done // wait until done signal arrives }
another alternative signal completion closing channel:
func sayhello(done chan struct{}) { := 0; < 10; i++ { fmt.print(i, " ") } if done != nil { close(done) // signal we're done } } func main() { sayhello(nil) // passing nil: don't want notification here done := make(chan struct{}) go sayhello(done) <-done // receive closed channel returns 0 value }
notes:
according edits/comments: if want 2 running sayhello()
functions print "mixed" numbers randomly: have no guarantee observe such behaviour. again, see aforementioned answer more details. go memory model guarantees events happen before other events, have no guarantee how 2 concurrent goroutines executed.
you might experiment it, know result not deterministic. first have enable multiple active goroutines executed with:
runtime.gomaxprocs(2)
and second have first start sayhello()
goroutine because current code first executes sayhello()
in main goroutine , once finished starts other one:
runtime.gomaxprocs(2) done := make(chan struct{}) go sayhello(done) // first start goroutine sayhello(nil) // , call sayhello() in main goroutine <-done // wait completion
Comments
Post a Comment