关于C++的std::call_once,其他线程咋处理

为什么不直接在 ctor 里调用 loadModel?
■网友
获取返回值的丑陋方法......
bool AdAnalysis::initialize(const char* modelPath){ bool result = false; std::call_once(this-\u0026gt;initDataFlag, () { result = this-\u0026gt;loadModel(modelPath); }); return result;} 【关于C++的std::call_once,其他线程咋处理】 call_once的问题, 粗略看了一下llvm的源码. 多个线程同时进入call_once, 只有一个线程能真正执行传递进去的函数, 其它线程则直接从call_once返回.

■网友
自己体会加粗的那句话。
std::call_once - cppreference.com
Executes the Callable object f exactly once, even if called from several threads.
Each group of call_once invocations that receives the same std::once_flag object will meet the following requirements:
Exactly one execution of exactly one of the functions (passed as f to the invocations in the group) is performed. It is undefined which function will be selected for execution. The selected function runs in the same thread as the call_once invocation it was passed to.No invocation in the group returns before the above-mentioned execution of the selected function is completed successfully, that is, doesn\u0026#39;t exit via an exception.If the selected function exits via exception, it is propagated to the caller. Another function is then selected and executed.


    推荐阅读