当没有线路调用时,控制如何转到golang中的主goroutine?

问题描述 投票:1回答:1
// _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

控制如何从第46行转到18?

go concurrency channel goroutine
1个回答
1
投票

当您将Go应用编译为可执行二进制文件时,编译器会在二进制文件中包含运行时。运行您的应用程序时,此运行时负责调度和运行goroutine。

在第17行中,您启动了goroutine,因此运行时将计划与main goroutine并发运行,并且可能并行运行(如果有足够的内核并且GOMAXPROCS允许它,有关详细信息,请参见Concurrency is not parallelism。] >

Spec: Go statements:

函数值和参数在调用goroutine中照常进行评估,但与常规调用不同,程序执行不等待被调用函数完成。相反,该函数开始在新的goroutine

中独立执行。当函数终止时,其goroutine也终止。如果函数具有任何返回值,则在函数完成时将其丢弃。
热门问题
推荐问题
最新问题