Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 931
Tony The Lion Avatar asked Dec 22 '10 13:12

Tony The Lion


People also ask

Is a static function thread safe?

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.

How do I make a static variable thread safe?

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.

What limitations does a static member function have?

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 .

What makes a function thread safe?

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.


1 Answers

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.

like image 167
sharptooth Avatar answered Sep 19 '22 23:09

sharptooth