static member functions thread safe?
Are static member functions thread-safe if they only access local variables (declared in the function scope)? That is, it's not clear to me whether locals in a static member function are in essence static themselves or not and thus each thread would have its own when it calls such a member.
A static-member function is just the same as a free (global) function. Local variables in any kind of function are always "stack variables" (private to the function/thread).
A thread cannot "own" a function, or have a "copy" of it. A function, from the processor's point of view, is an address in memory at which there is a set of instructions. A call to a static member function or a global function involves jumping to that address, regardless of which thread the call originated from. Each thread has its own stack, however, which means that local variables will not interfere with one another.
I know each thread has a separate stack, and indeed one specifies the stack when creating a new thread using OS functions as opposed to libraries that hide it. Rather, my question derives from static local variables being on the heap and thus shared. What I wasn't sure of was whether local auto variables in a static member function might not be implicitly like static variables in terms of storage--because the function itself is static. That's what I needed clarified, I didn't know if autos in static member functions are in thread-local stacks the way autos in a non-static member function are.
Well looks like the solution for thread-local static-like is to use C++0x thread_local. As there's no common compiler support,
#if defined _MSC_VER || defined __ICL
#define thread_local __declspec(thread)
#elif defined __GNUC__ || defined __ICC
#else
#define thread_local __thread
#error "Unsupported environment"
#endif
#if defined _MSC_VER || defined __ICL
#define thread_local __declspec(thread)
#elif defined __GNUC__ || defined __ICC
#else
#define thread_local __thread
#error "Unsupported environment"
#endif
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement