- Examples

Let’s discuss the examples of thread-safe initialization of data in this lesson.

We'll cover the following...

Example 1

The short example demonstrates the application of std::call_once and the std::once_flag. Both are declared in the header <mutex>.

Press + to interact
// safeInitializationCallOnce.cpp
#include <iostream>
#include <thread>
#include <mutex>
std::once_flag onceFlag;
void do_once(){
std::call_once(onceFlag, [](){ std::cout << "Only once." << std::endl; });
}
int main(){
std::cout << std::endl;
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();
std::cout << std::endl;
}

Explanation

  • The program starts four threads (lines 17 - 20). Each of them invokes do_once. The string “only ...

Access this course and 1400+ top-rated courses and projects.