3 回答
TA贡献1951条经验 获得超3个赞
这是一个没有通道但缺少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运算符阻止使用/访问返回值,但可以使用签名中返回占位符的指针来完成
- 3 回答
- 0 关注
- 175 浏览
添加回答
举报