Std::call_once 多线程库中只被调用一次函数实现方法 保证f只被调用一次 fox 库可由github.com/jiayuehua/fox中查看

#include <iostream>
#include <utility>
#include <fox/thread.hpp>
#include <mutex>
struct OnceFlag {
  std::mutex m_;
  bool hascalled_ = false;
};
 template< class Callable, class... Args >
void callOnce(OnceFlag& flag, Callable&& f, Args&&... args)
 
{
  std::scoped_lock l(flag.m_);
  if (!flag.hascalled_)
  {
    flag.hascalled_ = true;
    std::forward<Callable>(f)(std::forward<Args>(args)...);
  }
}
//例子 
OnceFlag onceflag;
void OnlyOnce()
{
  std::cout &lt;&lt; "OnlyOnce!\n";
}
  
void ThreadFoo()
{
  callOnce(onceflag, OnlyOnce);
}
  
int main()
{
  fox::Thread t(ThreadFoo);
  fox::Thread t1(ThreadFoo);
  fox::Thread t2(ThreadFoo);
  fox::Thread t3(ThreadFoo);
}

输出 OnlyOnce!