std::call_once

From Cppreference

Jump to: navigation, search
Defined in header <mutex>

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

Executes the function f exactly once, even if called from several threads.

Each group of call_once invocations, which receives the same std::once_flag object, follows the following requirements:

Contents

[edit] Parameters

flag - an object, for which exactly one function gets executed
f - function to call
args... - arguments to pass to the function

[edit] Return value

(none)

[edit] Exceptions

[edit] Example

#include <iostream>
#include <thread>
#include <mutex>
 
std::once_flag flag;
 
void do_once()
{
    std::call_once(flag, [](){ std::cout << "Called once" << std::endl; });
}
 
int main()
{
    std::thread t1(do_once);
    std::thread t2(do_once);
    std::thread t3(do_once);
    std::thread t4(do_once);
 
    t1.join();
    t2.join();
    t3.join();
    t4.join();
}

Output:

Called once

[edit] See also

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