简体   繁体   中英

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?

它们是本地的,除非你声明它们是static - 函数的每个invokation都有自己的变量副本,你不需要保护它们。

myint是当地的somefunc ,你并不需要保护它跨线程。

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.

myint变量将保持本地,不需要保护它们,因为每个线程都不会共享局部变量。

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 function RetType SomeFunc(Type arg)

Regards,
Marcin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM