jeudi 22 décembre 2016

Thread safety of static initialized unsafe call

Somewhere in a library I've a function which looks like -

inline int getIword()
{
    static int i = std::ios_base::xalloc();
    return i;
}

Now you can read about std::ios_base::xalloc() call here, but I want to emphasize this line from the metioned link -

This function is thread-safe; concurrent access by multiple threads does not result in a data race. (since C++14)

It says "since C++14" but I need C++11 support too. Since the function call is actually initializing a static local variable of getIword() method and we know local static variable initialization is thread safe for C++11 code, is it safe to assume this code is -

  • safe if there is only subsequent read calls made to function, eg. auto something = getIword().

  • safe? in case of code such as given below:

...

{
    if (value == ...) {
        os.iword(getIword()) = 1;
    } else if (value == ...) {
        os.iword(getIword()) = 0;
    }
    return os;
}

...

and if it is unsafe in the later example, where should I put the lock_guards to make it safe for C++11? Around return i or whole method or where call is being made?

Aucun commentaire:

Enregistrer un commentaire