Tony The Lion
Tony The Lion

Reputation: 63200

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?

Upvotes: 10

Views: 4275

Answers (6)

Marcin
Marcin

Reputation: 917

The static key-word means that the function will not be passed a hidden "this" argument. Also the function will not have access to the class instance data. The static qualifier of function, has no impact on function's local data.

The static RetType SomeClass::SomeMethod(Type arg) has the same "type" as a free functionRetType SomeFunc(Type arg)

Regards,
Marcin

Upvotes: 1

tengomucho
tengomucho

Reputation: 806

The myint variable will stay local, there is no need to protect them since each thread will not share the local variables.

Upvotes: 1

Pace
Pace

Reputation: 43817

myint will truly be local. You don't have to worry about protecting it. A separate space will be created on the stack for myint for every single function call in memory.

Upvotes: 1

AndersK
AndersK

Reputation: 36082

myint in your example is a local variable, every time somefunc is called myint lives. but not more than that.

myint doesn't need to be protected because its a local variable

Upvotes: 1

sharptooth
sharptooth

Reputation: 170499

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.

Upvotes: 10

ognian
ognian

Reputation: 11541

myint is local for somefunc and you don't need to protect it across threads.

Upvotes: 1

Related Questions