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 2024-03-14 15:33  Getone超  阅读(21)  评论(0编辑  收藏  举报