开发者

local variables of static member functions

Today we came accross a problem concerning static member functions in an multithreaded environment. The question we asked ourselves and couldn't find a satisfying answer is: are local varialbes of static member functions static as well?

// header

开发者_如何学Pythonclass A
{
  static int test();
}

// implementation
int A::test()
{
  int a = rand();
  int b = rand();
  int c = a + b;

  return c;
}

Say you have two threads both calling A::test(). Is it possible that while thread 1 proccesses c = a + b thread 2 enters test() and changes the value of a by assigning the new return value of rand() or in other words do both threads operate an the some memory locations for a, b and c?


No. The stack frames are independent for each thread's invocation of the function, and each gets its own locals. (You do need to be careful if you're accessing actual shared data e.g. static members in the class.)


Unless explicitly declared as static, no they're not. They're on a stack, and each thread has a separate stack.


The storage class of a, b, and c are (implicitly) auto which usually means on the call stack. They don't "inherit" static storage class from the method signature (which is a different meaning of static (yay for grossly overloaded keywords!)).


No, a, b, and c are not static.

Here's a sample that illustrates this:

class Val
{
public:
    Val() { cout << "Val" << this << endl; }
    ~Val() { cout << "~Val" << this << endl; }
    int n_;
};

class A
{
public:
    static int test()
    {
        Val a;
        a.n_ = rand();
        Val b;
        b.n_ = rand();
        Val c;
        c.n_ = a.n_ + b.n_;
        return c.n_;
    }
};

int main()
{
    srand(time(0));
    for( int i = 0; i < 5; ++i )
    {
        cout << "Test = " << A::test() << endl;
    }

    return 0;

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜