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

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)