dongshilve4392 2015-01-06 05:04
浏览 364
已采纳

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

How to make two functions calls f1(2) and f1(1) execute in parallel so that all the program would execute for 2 seconds not for 3.

package main

import (
    "fmt"
    "time"
)

// sleeps for `secs` seconds
func f1(secs time.Duration) (result string) {
    fmt.Printf("waiting %V
", 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()
}

playground

I guess I can do it only with channels. Should I redefine function f1 or I can leave it as is and change only way I call it?

  • 写回答

2条回答 默认 最新

  • douqiang3768 2015-01-06 05:15
    关注

    Use chan/goroutine

    package main
    
    import (
        "fmt"
        "time"
    )
    
    // sleeps for `secs` seconds
    func f1(secs time.Duration) (result string) {
        fmt.Printf("waiting %v
    ", secs)
        time.Sleep(secs * time.Second)
        result = fmt.Sprintf("waited for %v 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 := make(chan string)
        out2 := make(chan string)
        go func() {
            out1 <- f1(2)
        }()
        go func() {
            out2 <- f1(1)
        }()
        f2(<-out1, <-out2)
    }
    
    func main() {
        runNotParallel()
        runParallel()
    }
    

    https://play.golang.org/p/G4RHiq9LJw

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配