登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-04 16:30:40 325浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《当没有线路调用时,控制权如何转到主 goroutine?》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

// _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 应用程序编译为可执行二进制文件时,编译器会在二进制文件中包含运行时。当运行你的应用程序时,这个运行时负责调度和运行 goroutine。

在第 17 行中,您启动了一个 goroutine,因此运行时将安排它与 main goroutine 同时运行,并且可能并行运行(如果有足够的内核并且 GOMAXPROCS 允许,有关详细信息,请参阅 Concurrency is not parallelism)。

Spec: Go statements:

函数值和参数在调用 goroutine 中照常计算,但与常规调用不同,程序执行不会等待调用的函数完成。相反,该函数开始在新的 goroutine 中独立执行。当函数终止时,它的 goroutine 也会终止。如果函数有任何返回值,它们将在函数完成时被丢弃。

今天关于《当没有线路调用时,控制权如何转到主 goroutine?》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>