Jump to content
  • Advertisement
Sign in to follow this  

static member functions thread safe?

This topic is 2939 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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).

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!