C++11 std::call_once std::once_flag

本文深入解析了C++标准库中的std::call_once函数和std::once_flag类,阐述了如何确保线程安全下仅执行一次操作。通过实例演示了不同场景下call_once的行为,包括正常执行、异常处理和并发调用。

一 简介

1 std::call_once

头文件<mutex>

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

用途:准确执行一次可调用 (Callable) 对象 f ,即使同时从多个线程调用。

注意:

If, by the time call_once is called, flag indicates that f was already called, call_once returns right away (such a call to call_once is known as passive).
Otherwise, call_once invokes ​std​::​forward<Callable>(f) with the arguments std​::​forward<Args>(args)... (as if by std::invoke). Unlike the std::thread constructor or std::async, the arguments are not moved or copied because they don't need to be transferred to another thread of execution. (such a call to call_once is known as active).
         If that invocation throws an exception, it is propagated to the caller of call_once, and the flag is not flipped so that another call will be attempted (such call to call_once is known as exceptional).
        If that invocation returns normally (such call to call_once is known as returning), the flag is flipped, and all other calls to call_once with the same flag are guaranteed to be passive.


All active calls on the same flag form a single total order consisting of zero or more exceptional calls, followed by one returning call. The end of each active call synchronizes-with the next active call in that order.

The return from the returning call synchronizes-with the returns from all passive calls on the same flag: this means that all concurrent calls to call_once are guaranteed to observe any side-effects made by the active call, with no additional synchronization.

若在调用call_once时,flag指示已经调用了f,则call_once立即返回(称这种为对call_once的消极调用)。否则,call_once 以参数 std​::​forward<Args>(args)... 调用std​::​forward<Callable>(f)(如同用 std::invoke)。不同于std::thread构造函数或std::async,call_once 不移动或复制参数,因为不需要转移它们到另一执行线程(称这种为对 call_once 的积极调用)。
        若该调用抛异常,则传递异常给call_once的调用方,并且不翻转flag ,其他调用将尝试执行(这种对call_once的调用被称为异常)。
        若该调用正常返回(这种对call_once的调用被称为返回),则翻转 flag ,并保证以同一 flag 对call_once的其他调用为消极。

2  std::once_flag

头文件<mutex>

class once_flag; (C++11 起)

类 std::once_flag 是 std::call_once 的辅助类。
std::once_flag 既不可复制亦不可移动。
once_flag的生命周期必须要比使用它的线程的生命周期要长

二 举例

#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();

  getchar();
}

结果:

三 参考

std::call_once

std::once_flag 

<think>我们正在讨论C++中的std::once_flagstd::call_once。这两个工具用于确保某个函数只被调用一次,即使在多线程环境下也是如此。这通常用于实现线程安全的单例模式,或者初始化只应执行一次的资源。 我们将首先解释这两个组件的用途和基本用法,然后给出一个示例代码,最后根据内容提出相关问题。 </think>### `std::once_flag` 与 `std::call_once` 的用法 `std::once_flag` 和 `std::call_once` 是 C++11 引入的线程安全初始化工具,用于确保某个操作在多线程环境中仅执行一次,比双重检查锁定更简洁安全。以下是核心要点和用法: #### **核心作用** 1. **`std::once_flag`**: - 状态标志,记录关联操作是否已执行(不可复制,不可移动)。 2. **`std::call_once`**: - 接受一个 `once_flag` 和可调用对象(如函数、lambda)。 - **保证**:无论多少线程调用,可调用对象仅执行一次。 --- #### **使用步骤** 1. 声明全局/静态的 `once_flag` 对象(通常与单例关联)。 2. 在需要初始化的位置调用 `std::call_once`,传入操作逻辑。 #### **示例:线程安全的单例模式** ```cpp #include <mutex> class Singleton { public: static Singleton& getInstance() { std::call_once(initFlag, []() { instance.reset(new Singleton); }); return *instance; } private: Singleton() {} // 私有构造函数 static std::unique_ptr<Singleton> instance; static std::once_flag initFlag; // 初始化标志 }; // 静态成员初始化 std::unique_ptr<Singleton> Singleton::instance; std::once_flag Singleton::initFlag; ``` #### **关键特性** - **隐式同步**:内部通过锁和原子操作保证线程安全,无需手动管理内存顺序。 - **异常安全**:若操作抛出异常,其他线程会重新尝试执行。 - **替代场景**: - 替代双重检查锁定,避免指令重排风险。 - 初始化全局配置、日志系统等需一次性执行的资源。 --- #### **与双重检查锁定的对比** | 特性 | `std::call_once` | 双重检查锁定 | |---------------------|--------------------------------|--------------------------| | **复杂度** | 更简洁(无需显式锁/原子操作) | 需手动处理内存顺序和锁 | | **安全性** | 无指令重排风险 | 需谨慎使用 `volatile`/原子 | | **适用性** | C++11 及以上 | 跨语言通用 |
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值