猿问

golang 函数:带返回的并行执行

如何使两个函数调用f1(2)并f1(1)并行执行,以便所有程序执行 2 秒而不是 3 秒。


package main


import (

    "fmt"

    "time"

)


// sleeps for `secs` seconds

func f1(secs time.Duration) (result string) {

    fmt.Printf("waiting %V\n", secs)

    time.Sleep(secs * time.Second)

    result = fmt.Sprintf("waited for %d seconds", secs)

    return

}


// prints arg1, arg2

func f2(arg1, arg2 string) {

    fmt.Println(arg1)

    fmt.Println(arg2)

}


// this function executes for 3 seconds, because waits a lot

func runNotParallel() {


    out1 := f1(2)

    out2 := f1(1)

    f2(out1, out2)


}


// golang parallel return functions

// todo: make it run so all the function will executes for 2 seconds not for 3

func runParallel() {

    out1 := f1(2)

    out2 := f1(1)

    f2(out1, out2)

}


func main() {

    runNotParallel()

    runParallel()

}



我想我只能通过渠道来做到这一点。我应该重新定义函数f1还是可以保持原样并仅更改我调用它的方式?


慕斯王
浏览 176回答 3
3回答

饮歌长啸

这是一个没有通道但缺少f2同步的解决方案:package mainimport (    "fmt"    "sync"    "time")// sleeps for `secs` secondsfunc f1(secs time.Duration, result *string, sg *sync.WaitGroup) () {    fmt.Printf("waiting %v\n", secs)    time.Sleep(secs * time.Second)    *result = fmt.Sprintf("waited for %d seconds", secs)    if sg!= nil {        sg.Done()    }    return}// prints arg1, arg2func f2(arg1, arg2 string) {    fmt.Println(arg1)    fmt.Println(arg2)}// this function executes for 3 seconds, because waits a lotfunc runNotParallel() {    var out1, out2 string    f1(2, &out1, nil)    f1(1, &out2,nil)    f2(out1, out2)}// golang parallel return functions// todo: make it run so all the function will executes for 2 seconds not for 3func runParallel() {    var sg sync.WaitGroup    sg.Add(2)    var out1, out2 string    go f1(2, &out1, &sg)    go f1(1, &out2, &sg)    sg.Wait()    f2(out1, out2)}func main() {    runNotParallel()    runParallel()}基本上,go运算符阻止使用/访问返回值,但可以使用签名中返回占位符的指针来完成
随时随地看视频慕课网APP

相关分类

Go
我要回答