Sign in to follow this  
Prune

static member functions thread safe?

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this