开发者

static member function and thread-safety

In C++, when you have local variables in a static member function, does it mean those local variabl开发者_StackOverflow中文版es 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?


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.


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


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


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.


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


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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜