Search code examples
c++multithreadingstatic-functions

static member function and thread-safety


In C++, when you have local variables in a static member function, does it mean those local variables are also implicitly static or are they really local?

example:

static void myClass::somefunc(int someint)
{

int myint = someint;  // is myint really a local variable or does it change due to the static qualifier at function level?


}

Also, different threads from a thread pool running this function, does myint need to be protected by a lock? assuming that all values passed to it are different and have no relation to each other.

EDIT: Thanx for the answers. Now what if I passed in a boost::shared_ptr<T>, knowing that this object would not be concurrently being used by another thread? (Not sure if one can really guarantee that, or can you?)

I guess a raw ptr passed in, would need some protection, if it were being used all over?


Solution

  • They are local unless you declare them static - each invokation of the function will have its own copy of the variable and you don't need to to protect them.