W. Verbeke
W. Verbeke

Reputation: 355

Ensure thread-safety of static boolean check

A pattern that occurs several times in my code is a function that requires a certain initialization function to be called, which is currently solved as follows

void doSomething(){
    static bool _isInitialized = false;
    if( ! _isInitialized ){
        initializationFunction();
        _isInitialized = true;
    }
    ...
}

This kind of function is however not thread-safe as far as I understand since it can occur that one thread is executing initializationFunction and another thread starts doing the same before _isInitialized is set to true.

I am new to writing multithreaded code, and am wondering what would be a good way to make such code thread-safe. One possible solution seems to be to put a lock around this code, but I would rather avoid using locks. Is there another (better) way to solve this?

Upvotes: 2

Views: 164

Answers (2)

W. Verbeke
W. Verbeke

Reputation: 355

As suggested by 'Some programmer dude', a possible solution is to use std::call_once. The code could then be rewritten as:

void doSomething(){
    static std::once_flag flag;
    std::call_once( initializationFunction, flag );
    ...
}

Upvotes: 1

G.M.
G.M.

Reputation: 12879

Assuming the signature of initializationFunction is up to some third party (as suggested in the comments) then you can do something like...

void doSomething ()
{
    static bool _isInitialized =
        []()
        {
            initializationFunction();
            return true;
        }();
}

Upvotes: 3

Related Questions