Golang:在特定情况下一次评估函数的最佳方法

问题描述

假设我有一个Eval结构,并且多个goroutine可以调用Evaluate方法获取result字段的值。以下是代码的基本结构:

type Eval struct {
    done  bool
    result interface{}
}

func (e *Eval) Evaluate(f func() interface{}) interface{} {
    if e.done == false {
        e.result = f()
        e.done = true
    }
    return e.result
}

由于作为Evaluate方法的参数传递的函数可能需要花费一些时间才能执行,因此我想避免多次调用函数。实际上,只有第一个调用Evaluate函数的goroutine才会“评估”结果的值。其他goroutine将仅等待结果字段准备就绪。

这是我想出的:

type Eval struct {
    mu    *sync.Mutex
    cond  *sync.Cond // cond uses mu as sync.Locker
    once  *sync.Once
    done  bool
    result interface{}
}

func (e *Eval) Evaluate(f func() interface{}) interface{} {
    go e.once.Do(func() {
        defer e.cond.broadcast()

        v := f()
        e.mu.Lock()
        e.result = v
        e.done = true
        e.mu.Unlock()
    })

    e.mu.Lock()
    if e.done == false {
        e.cond.Wait()
    }
    v := e.result
    e.mu.Unlock()
    return v
}

但是我觉得这太过分了,使用sync.Mutex来控制对将被写入一次并读取多次的变量的访问不是有效的解决方案。实现我想要的最好,最“ golang”方法是什么?

编辑:如comment中所述,仅使用sync.Once可以完成工作。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)