static member functions and thread-safety

Tony The Lion picture Tony The Lion · Jan 6, 2011 · Viewed 24.4k times · Source

Objects and variables created in a static member function are not considered 'local' as they would in a member function, so that they can now be shared amongst multiple threads right?

Whereas if you have a member function which creates some object, this would be local to the thread and therefore it is non-shared.

Am I correct in saying this?

Answer

Michael J picture Michael J · Jan 6, 2011

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.