Search code examples
c++static-variables

Static member variables in multithreading


As all of you know, despite how many objects instantiated, only one instance of static member variables are stored in the BSS segment. Accordingly, consider having some thread which instantiates a class with a static member variable and changes static member frequently; my question is whether the static member is thread-safe or not.


Solution

  • Variables do not know anything about threads. Class static member variables are not inherently thread-safe. You might consider putting them in thread-local storage, or making sure the members' data structures are themselves thread-safe.

    You also mentioned "static member functions" but those are immaterial to this question: it doesn't matter how you modify your static member variables, doing so is not inherently thread-safe, whether modified via static member functions, regular member functions, or non-member functions.