栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

goroutines执行顺序

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

goroutines执行顺序

您没有任何内容可以显式同步两个goroutine的顺序。如果运行足够的时间,您将看到调用以

fmt.Println
不同的顺序进行打印。当执行goroutine时,由于它们是并发操作,因此无法保证它们将何时执行和/或完成。您需要使用各种标准库程序包或通道本身来同步并发运行的goroutine的执行。

例如(通过利用渠道的封锁性,您可以执行以下操作):

func main() {    c := make(chan int)    go sum([]int{1, 2, 3}, c)    //use the channel to block until it receives a send    x := <-c    fmt.Println(x)    //then execute the next routine    go sum([]int{4, 5, 6}, c)    x = <-c    fmt.Println(x)}

另一个示例(显然不那么实用,但是在这里查看其他常见的go同步功能),您可以引入一个等待组和一个通道范围:

func sum(a []int, c chan int, wg *sync.WaitGroup) {    defer wg.Done()    fmt.Println("summing: ", a)    total := 0    for _, v := range a {        total += v    }    //fmt.Println("send to c",total)    c <- total // send total to c}func main() {    c := make(chan int)    wg := new(sync.WaitGroup)    //concurrently call the concurrent calls to sum, allowing execution to continue to the range of the channel     go func() {        //increment the wait group, and pass it to the sum func to decrement it when it is complete        wg.Add(1)        go sum([]int{1, 2, 3}, c, wg)        //wait for the above call to sum to complete        wg.Wait()        //and repeat...        wg.Add(1)        go sum([]int{4, 5, 6}, c, wg)        wg.Wait()        //all calls are complete, close the channel to allow the program to exit cleanly         close(c)    }()    //range of the channel    for theSum := range c {        x := theSum        fmt.Println(x)    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/471149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号