D
D
dyxism2014-03-10 14:32:22
go
dyxism, 2014-03-10 14:32:22

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")
}

On the page where I found this example - https://gobyexample.com/goroutines, the following output is written:

$ go run goroutines.go
direct : 0
direct : 1
direct : 2
goroutine : 0
going
goroutine : 1
goroutine : 2
done

But if you run the example here - play.golang.org/p/aIO_Wi3hJj
the output is:

direct : 0
direct : 1
direct : 2
done

ps Right now I'm trying to write a script where you need to execute a function in several threads, but as a result, the execution of this function is ignored, approximately as it turns out here.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
miolini, 2014-03-12
@dyxism

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()
}

Q
q1t, 2014-03-10
@q1t

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 question

Ask a Question

731 491 924 answers to any question