c++ call_once 使用详解

c++ call_once 使用详解

std::call_once

  • 头文件 #include <mutex>

  • 函数原型:

    cpp 复制代码
    template<class Callable, class... Args>
    void call_once(std::once_flag& flag, Callable&& f, Args&&... args);
    • flag:标志对象,用于指示 f 是否已调用过。
    • f:要调用的可调用对象。
    • args:传递给 f 的参数。
  • 作用:保证可调用对象 f 只被执行一次,即使同时从多个线程调用。

  • 注意事项:

    • 如果在调用 std::call_once 的时刻,flag 指示 f 已经调用过,那么 std::call_once 会立即返回。
    • 如果在调用 f 时抛出了异常,那么异常将传播给 std::call_once 的调用方,并且 flag 不会被翻转。
    • 如果调用正常返回,那么 flag 被翻转,并保证以同一 flag 对 std::call_once 的其他调用立即返回。
    • 如果有多个线程同时在 flag 未翻转时调用 std::call_once,那么这些调用将被组成单独全序,并被依次执行。

示例代码

cpp 复制代码
#include <cstdio>
#include <mutex>
#include <thread>

std::once_flag flag1, flag2;

void simple_do_once()
{
    std::call_once(flag1, []() { printf("only call once\n"); });
}

void may_throw_function(bool do_throw)
{
    if (do_throw) {
        printf("throw, try again...\n");
        throw std::exception();
    }
    printf("no throw, call once\n");
}

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);
    st1.join();
    st2.join();

    std::thread t1(do_once, true);
    std::thread t2(do_once, false);
    std::thread t3(do_once, true);
    t1.join();
    t2.join();
    t3.join();
}
相关推荐
Elastic 中国社区官方博客11 分钟前
使用 Elastic 进行网络监控:统一网络可观测性
大数据·开发语言·网络·人工智能·elasticsearch·搜索引擎·全文检索
Codefengfeng14 分钟前
Python Base环境中加包的方法
开发语言·python
清水白石00815 分钟前
《Python 编程全景解析:从核心精要到测试替身(Test Doubles)五大武器的实战淬炼》
开发语言·python
额,不知道写啥。2 小时前
HAO的线段树(中(上))
数据结构·c++·算法
六件套是我2 小时前
无法访问org.springframeword.beans.factory.annotation.Value
java·开发语言·spring boot
LYS_06182 小时前
C++学习(5)(函数 指针 引用)
java·c++·算法
S-码农2 小时前
Linux ——条件变量
linux·开发语言
清水白石0082 小时前
《Python 编程全景解析:从核心精要到 Hypothesis 属性基测试的边界探索》
开发语言·python
IT枫斗者2 小时前
IntelliJ IDEA 2025.3史诗级更新:统一发行版+Spring Boot 4支持,这更新太香了!
java·开发语言·前端·javascript·spring boot·后端·intellij-idea