static member functions and thread-safety static member functions and thread-safety multithreading multithreading

static member functions and thread-safety


Consider this class

class CData{public:    static void func()    {        int a;        static int b;    }    int c;    static int d;};int main(){    CData::func();}

Now variable a is local to each call of func(). If two threads call func() at the same time, they get different versions of a.

b is a static local. The value persists between different calls of func(). If two threads call func() at the same time, they access the same version of b so they might need to do synchronisation.

c is an instance variable; it is attached to a particular instantiation of CData. func() cannot access c, except with a trick I'll show below.

d is a static variable. There is one instance of d shared between all uses of class CData so synchronisation may be necessary. It can be used easily from the static function func().

The trick used to access instance data from a static function is to pass a valid object into the function.

e.g.

class CData{public:    static void func(CData *p)    {        int a;        static int b;        b = p->c;    }    int c;    static int d;};int main(){    CData data;    CData::func(&data);}

Hope that helps.


No you are not correct.

Objects created in a static function are not shared, and this is also the case for any normal functions.

Objects can be shared though if they are declared static themselves, and it does not depends if the function is static or not.

void myFunc(){    static MyObject o;    o.CallMethod(); // here o is shared by all threads calling myFunc}

When an object is declared static, it is as if the object was a global variable, but only visible in the scope of the function that it is declared into.


No you are not correct. And yes, C++ does very much overuse the word "static".

A static class member variable is of course a global with the class acting as a namespace scope and with some access privilege differences if it is private or protected (can only be accessed by the class).

However a static class member function is just like a regular free-function (not class member) and has its own local variables every time it is called.

The only real difference between a static class member function and a regular free-function, apart from its naming convention, is that it has access to private members of a class (and needs an external "instance" of one).

In addition a static class member function can be called from a template with a variable template parameter, invoking what is commonly called "compile-time polymorphism" and is commonly used in meta-programming.

A static "local" variable in any function is a single-instance, on the other hand, is also a bit like a global and is sensitive to thread-contention issues as two threads calling the function access the same instance.