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.


 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">