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?
No, static functions are not inherently thread-safe. Even your simple example isn't. Assuming both intvariable and stringvariable are supposed to be updated at the same time, another thread could observe the state of c1 between the two assignments, leading to data corruption.
As for the original question - Hashtable by itself is synchronized. So, if you are declaring a static final Hashtable and also intializing it at the time of declaration itself, all operations will be thread-safe on this Hashtable instance without you having to write any code for synchronization.
A static member function cannot be declared with the keywords virtual , const , volatile , or const volatile . A static member function can access only the names of static members, enumerators, and nested types of the class in which it is declared. Suppose a static member function f() is a member of class X .
A threadsafe function protects shared resources from concurrent access by locks. Thread safety concerns only the implementation of a function and does not affect its external interface. The use of global data is thread-unsafe.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With