How does control go to a main goroutine when no line calls it?

Issue

// _Closing_ a channel indicates that no more values
// will be sent on it. This can be useful to communicate
// completion to the channel's receivers.

package main

import "fmt"

// In this example we'll use a `jobs` channel to
// communicate work to be done from the `main()` goroutine
// to a worker goroutine. When we have no more jobs for
// the worker we'll `close` the `jobs` channel.
func main() {
    jobs := make(chan int, 5)
    done := make(chan bool)

    fmt.Println("1")
    go func() {
        for {
                fmt.Println("4")
            j, more := <-jobs
            if more {
                fmt.Println("received job", j)
            } else {
                fmt.Println("received all jobs")
                done <- true
                return
            }
        }
    }()

    fmt.Println("2")
    // This sends 3 jobs to the worker over the `jobs`
    // channel, then closes it.
    for j := 1; j <= 3; j++ {
            fmt.Println("3", j)
        jobs <- j
        fmt.Println("sent job", j)
    }

    fmt.Println("5")
    close(jobs)

    fmt.Println("6")
    fmt.Println("sent all jobs")
    //How does control go from here to the main's go routine - line 18. Who call's it? and How?

    // We await the worker using the
    // [synchronization](channel-synchronization) approach
    // we saw earlier.
    <-done

    fmt.Println("7")
}

https://play.golang.org/p/Xe_wh3YTmwk

How does control go from line 46 to 18 ?

Solution

When you compile your Go app into an executable binary, the compiler includes a runtime in the binary. When running your app, this runtime is responsible for scheduling and running goroutines.

In line 17 you launch a goroutine, so the runtime will schedule to run it concurrently with the main goroutine, and possibly in parallel (if there are enough cores and GOMAXPROCS allows it, for details see Concurrency is not parallelism).

Spec: Go statements:

The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine. When the function terminates, its goroutine also terminates. If the function has any return values, they are discarded when the function completes.

Answered By – icza

Answer Checked By – David Marino (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.