首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

std::call_once

Defined in header <mutex>

?

?

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

?

(since C++11)

执行Callable对象f精确地一次,即使从几个线程调用。

每一组call_once接收相同调用的调用。std::once_flag对象将满足下列要求:

  • 正确执行其中一个函数%28,作为f对组中的调用执行%29。未定义将选择哪个函数执行。所选函数运行在与call_once调用被传递给。
  • 在成功完成上述函数的执行之前,组中的调用不会返回,即%27T通过异常退出。
  • 如果所选函数通过异常退出,则将其传播到调用方。然后选择并执行另一个函数。

参数

flag

-

an object, for which exactly one function gets executed

f

-

Callable object to invoke

args...

-

arguments to pass to the function

返回值

%280%29

例外

  • std::system_error如果有任何条件阻止对call_once按规定执行
  • 引发的任何异常f

注记

The arguments to the Callable object are moved or copied by value. If a reference argument needs to be passed to the Callable object, it has to be wrapped (e.g. with std::ref or std::cref).

(until C++17)

The arguments to the Callable object are perfect forwarded (as if by std::forward<Callable>(f) and std::forward<Args>(args))...), which is different from the uses of Callables in the thread constructor or std::async, because call_once does not have to transfer its arguments to another thread of execution, and therefore does not need to move or copy.

(since C++17)

初始化函数局部静力学即使是从多个线程调用时,也只能发生一次,并且可能比使用std::call_once...

二次

代码语言:javascript
复制
#include <iostream>
#include <thread>
#include <mutex>
 
std::once_flag flag1, flag2;
 
void simple_do_once()
{
    std::call_once(flag1, [](){ std::cout << "Simple example: called once\n"; });
}
 
void may_throw_function(bool do_throw)
{
  if (do_throw) {
    std::cout << "throw: call_once will retry\n"; // this may appear more than once
    throw std::exception();
  }
  std::cout << "Didn't throw, call_once will not attempt again\n"; // guaranteed once
}
 
void do_once(bool do_throw)
{
  try {
    std::call_once(flag2, may_throw_function, do_throw);
  }
  catch (...) {
  }
}
 
int main()
{
    std::thread st1(simple_do_once);
    std::thread st2(simple_do_once);
    std::thread st3(simple_do_once);
    std::thread st4(simple_do_once);
    st1.join();
    st2.join();
    st3.join();
    st4.join();
 
    std::thread t1(do_once, true);
    std::thread t2(do_once, true);
    std::thread t3(do_once, false);
    std::thread t4(do_once, true);
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

二次

可能的产出:

二次

代码语言:javascript
复制
Simple example: called once
throw: call_once will retry
throw: call_once will retry
Didn't throw, call_once will not attempt again

二次

另见

once_flag (C++11)

helper object to ensure that call_once invokes the function only once (class)

C呼叫文件[医]一次

代码语言:txt
复制
 ? cppreference.com

在CreativeCommonsAttribution下授权-ShareAlike未移植许可v3.0。

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com