多线程编程3. std::call_once

多线程编程3. std::call_once

1. 简介

std::call_once 的作用是,确保在多个线程中同时调用 call_once 时,只有一个线程能够成功执行 func 函数,而其他线程则会等待该函数执行完成。
注意 : std::call_once 只能在子线程中使用,在主线程中使用会报错

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

flag 是一个 std::once_flag 类型的对象,用于标记函数是否已经被调用;
func 是需要被调用的函数或可调用对象;
args 是函数或可调用对象的参数。

void test_call_once() {
	 cout << "test call_once" << endl;
}

void test_fun_time() {
	cout << "test begin" << endl;
	std::call_once(once_flg, test_call_once);
	cout << "test after" << endl;
}

int main()
{
	std::thread  th1(test_fun_time);
	std::thread  th2(test_fun_time);
	std::thread  th3(test_fun_time);
	th1.join();
	th2.join();
	th3.join();
	return 0;
}

运行结果
根据运行结果可以发现 std::call_once 只会被执行一次,只是执行到这的时候等待其他线程执行完之后,再接着往下执行。

2. 使用场景

  1. 多线程下的单例模式
  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值