sync.Once implementation

ε祈祈猫儿з 提交于 2019-12-02 13:44:10

Once.Do() does not return until f() has been executed once. Which means if multiple goroutines call Once.Do() concurrently, f() will be executed once of course, but all calls will wait until f() completes (they will be blocked).

Your proposed solution does not have this very important property! Yours only guarantees that f() will be executed only once, but if called from multiple goroutines concurrently, subsequent calls will return immediately, even if f() is still running.

When we use sync.Once, we rely on this behavior, we rely on f() being completed after calling Once.Do(), so we can use all variables that f() initialized safely, without having a race condition.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!