title: Is std::call_once lock free?
body: <p>I want to find out if the std::call_once lock free. <a href="https://codereview.stackexchange.com/questions/117468/stdonce-flag-and-stdcall-once-implementation">There</a> are call_once implementations using mutex. But why should we use mutex? I tried to write simple implementation using atomic_bool and CAS operation. Is the code thread safe?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;atomic&gt;
  #include &lt;unistd.h&gt;
  
  using namespace std;
  using my_once_flag = atomic&lt;bool&gt;;
  
  void my_call_once(my_once_flag&amp; flag, std::function&lt;void()&gt; foo) {
      bool expected = false;
      bool res = flag.compare_exchange_strong(expected, true,
                                              std::memory_order_release, std::memory_order_relaxed);
      if(res)
          foo();
  }
  my_once_flag flag;
  void printOnce() {
      usleep(100);
      my_call_once(flag, [](){
         cout &lt;&lt; "test" &lt;&lt; endl;
      });
  }
  
  int main() {
      for(int i = 0; i&lt; 500; ++i){
              thread([](){
                  printOnce();
              }).detach();
      }
      return 0;
  } 
  </code></pre>