Performing a task only once
Sometimes, we need to perform a certain task just one time. For example, in a multithreaded application, several threads may run the same function to initialize a variable. Any of the running threads may do it, but we want the initialization to be done exactly once.
The C++ Standard Library provides both std::once_flag
and std::call_once
to implement exactly that functionality. We will see how to implement this functionality using atomic operations in the next chapter.
The following example will help us to understand how to use std::once_flag
and std::call_once
to achieve our goal of performing a task just one time when more than one thread tries to do it:
#include <exception> #include <iostream> #include <mutex> #include <thread> int main() { std::once_flag run_once_flag; std::once_flag run_once_exceptions_flag; auto thread_function = [&] { ...