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

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

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页