Answer the question
In order to leave comments, you need to log in
How to solve problem with golang goroutines example?
There is an example for the Go language, using its lightweight goroutines. Please help me figure out why this example does not run correctly.
Example code:
// A _goroutine_ is a lightweight thread of execution.
package main
import "fmt"
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
// Suppose we have a function call `f(s)`. Here's how
// we'd call that in the usual way, running it
// synchronously.
f("direct")
// To invoke this function in a goroutine, use
// `go f(s)`. This new goroutine will execute
// concurrently with the calling one.
go f("goroutine")
// You can also start a goroutine for an anonymous
// function call.
go func(msg string) {
fmt.Println(msg)
}("going")
// Our two goroutines are running asynchronously in
// separate goroutines now, so execution falls through
// to here. This `Scanln` code requires we press a key
// before the program exits.
var input string
fmt.Scanln(&input)
fmt.Println("done")
}
$ go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done
direct : 0
direct : 1
direct : 2
done
Answer the question
In order to leave comments, you need to log in
Try it with this synchronization mechanism.
package main
import "fmt"
import "sync"
func main() {
waitGroup := sync.WaitGroup{}
waitGroup.Add(1)
go func() {
fmt.Println("Hello, playground")
waitGroup.Done()
}()
waitGroup.Wait()
}
play.golang.org/p/J0tgsi0U_E
the problem was in the input (maybe not supported in the sandbox) or maybe not in this one, but this example is working, it will run correctly on the local machine.
in the first option, for fidelity, you can synchronize the gortins, and then the result will be predictable.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question