golang 函数:使用 return 并行执行

golang functions: parallel execution with return

如何使两个函数调用 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()
}

playground

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

使用chan/goroutine

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 %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

另一种方法是使用 WaitGroup

我编写了这个实用函数来帮助并行化一组函数:

import "sync"

// Parallelize parallelizes the function calls
func Parallelize(functions ...func()) {
    var waitGroup sync.WaitGroup
    waitGroup.Add(len(functions))

    defer waitGroup.Wait()

    for _, function := range functions {
        go func(copy func()) {
            defer waitGroup.Done()
            copy()
        }(function)
    }
}

所以对于你的情况,我们可以这样做

value1 := ""
value2 := ""

func1 := func() {
    value1 = f1(2)
}

func2 = func() {
    value2 = f1(1)
}

Parallelize(func1, func2)

f2(out1, out2)

如果您想使用 Parallelize 函数,可以在这里找到 https://github.com/shomali11/util

这是一个没有通道但缺少 f2 同步的解决方案:

package main

import (
    "fmt"
    "sync"
    "time"
)

// sleeps for `secs` seconds
func 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, arg2
func f2(arg1, arg2 string) {
    fmt.Println(arg1)
    fmt.Println(arg2)
}

// this function executes for 3 seconds, because waits a lot
func 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 3
func 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 运算符会阻止 using/accessing 一个 return 值,但可以使用 return 占位符的指针来完成在签名中

go 1.18 支持泛型, 可读性更高。

func async[T any](f func() T) chan T {
    ch := make(chan T)
    go func() {
        ch <- f()
    }()
    return ch
}

func main() {
    startTime := time.Now().Local()

    out1 := async(func() string {
        time.Sleep(1 * time.Second)
        return "thing 1"
    })
    out2 := async(func() string {
        time.Sleep(2 * time.Second)
        return "thing 2"
    })

    results := []string{<-out1, <-out2}

    fmt.Printf("results: %v\n", results)
    fmt.Printf("took %v", time.Since(startTime))
}

playground

lo package 提供此功能以及许多其他通用辅助功能。