Jun 132016

I was watching a video series about concurrency recently and stumbled upon a function I hadn’t used before but is incredibly useful! Namely, std::call_once: http://en.cppreference.com/w/cpp/thread/call_once

It solves an interesting problem. Suppose you have some shared resource between threads for which the first time it is accessed something special should happen but only once. In the scenario presented in the video series, mutliple threads wish to access a log file to write to but the file only needs to be opened once. The funcction std::call_once and variable type std::once_flag provide an elegant way of doing that without the overhead of having to lock and unluck a mutex and check to see if the file has been opened already every time shared_print() is called.