posts - 35,comments - 0,views - 12303

std::call_once

中定义

template< class Callable, class... Args >
void call_once( std::once_flag& flag, Callable&& f, Args&&... args );

确保函数或者代码片段在在多线程环境下,只需要执行一次。

常用的场景如Init()操作或一些系统参数的获取等。

此函数在 POSIX 中类似 pthread_once

使用案例

#include <iostream>
#include <thread>
#include <mutex>
std::once_flag flag;
void Initialize()
{
std::cout << "Run into Initialize.." << std::endl;
}
void Init()
{
std::call_once(flag, Initialize);
}
int main()
{
std::thread t1(Init);
std::thread t2(Init);
std::thread t3(Init);
std::thread t4(Init);
t1.join();
t2.join();
t3.join();
t4.join();
}

std::once_flag

std::once_flagstd::call_once 的辅助类。

note:std::once_flag 既不可复制亦不可移动。

once_flag的生命周期必须要比使用它的线程的生命周期要长

posted on   Getone超  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)

点击右上角即可分享
微信分享提示