goroutines执行顺序

goroutines执行顺序,第1张

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5462992.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-12
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存