26

Lets say I have a class that after initialization creates a thread and runs a method in it, within it declares a static variable:

void method()
{
     static int var = 0;
     var++;
}

If I create more objects of the class, for example 3, then the method will be called 3 times in 3 different threads. After that var will equal 3. How to accomplish the functionality, where each thread has its own static var that is independent of others. I would appreciate all help.

3
  • 3
    Why not use member variable ?
    – Jarod42
    Jul 24, 2015 at 11:18
  • 2
    Because the needed variable is significant only for the scope of this method and not used anywhere else. For now I have used a member variable, but I am wondering either this wouldn't be better. The method is called periodically and the static var shouldnt change. Jul 24, 2015 at 11:19
  • 6
    Really? This sounds like you should really use a local variable not static, no member, just a local variable in the method-block!!! - Thread-locals like mentioned in the other answers can lead to a bunch of problems with memory leaks and similar in big applications, so should only be used when really necessary!
    – Falco
    Jul 24, 2015 at 14:11

4 Answers 4

51

You can use the thread_local keyword which indicates that the object has a thread storage duration. You can use it like that :

static thread_local int V;

If you want more information about storage class specifiers, you can check CppReference.

2
  • 2
    And in case your compiler does not support it yet, check out Boost's thread_local_storage, which does basically the same, but as a library. Jul 24, 2015 at 13:32
  • 1
    I am using c++11 so its ok. Jul 24, 2015 at 15:35
15

This is what the thread_local storage class specifier is for:

void method()
{
     thread_local int var = 0;
     var++;
}

This means that each thread will have its own version of var which will be initialized on the first run through that function and destroyed on thread exit.

3
  • 2
    I think this answer would be much better if you'd go over (or at least link to) possible performance implications of using thread local storage. Jul 24, 2015 at 15:10
  • 1
    @KubaOber: That's a different question. Jul 24, 2015 at 15:23
  • 1
    Sure, just link to it if you happen to know about one or two with good answers :) Jul 24, 2015 at 15:28
9

You said, in a comment:

I do want a variable that is specific for each instance of a class

That's precisely what an instance variable is (a.k.a. a per-instance member).

static members and function local variables are not specific to each instance of a class! They are either completely global (one instance per entire executable), or are per-thread if you use C++11 and declare them thread_local.

You absolutely need a member variable. That's the only way to guarantee that the variable will be specific for each instance of the class.

You might argue that you create a dedicated thread per each instance of the class. First of all, it's likely that you shouldn't be doing that. Secondly, if you ever change your mind, and stop creating a per-class thread and, say, use a thread pool instead, your code will instantly break.

So, the proper and straightforward thing is to have it as an instance variable (as opposed to a class variable):

// OK - instance variable
class C { int var; };

// WRONG - class variable and lookalikes
class C { static int var; };
class C { void foo() { static int var; } };

// WRONG - thread variable, but **not** instance variable
class C { static thread_local int var; };
class C { void foo() { static thread_local int var; } };

If you want, you can indicate your intent by including the method's name in the variable name:

class C {
  int foo_var;
  C() : foo_var(0) {}
  void foo() { ... }
};

Finally, if you're OK with a bit more typing, you can use a member wrapper to enforce the scope it's used in:

#include <utility>
#include <cassert>

template <typename T, typename Member, Member member>
class ScopedMember {
   T data;
public:
   explicit ScopedMember(const T & d) : data(d) {}
   explicit ScopedMember(T && d) : data(std::move(d)) {}
   ScopedMember() {}
   template <Member m, void(*)(char[member == m ? 1 : -1]) = (void(*)(char[1]))0>
   T & use() { return data; }
   template <Member m, void(*)(char[member == m ? 1 : -1]) = (void(*)(char[1]))0>
   const T & use() const { return data; }
};

class C {
public:
   C() : m_foo(-1) {}
   void granted() {
      auto & foo = m_foo.use<&C::granted>();
      foo = 5;
      assert(m_foo.use<&C::granted>() == 5);
   }
   void rejected() {
#if 0
      // Won't compile
      auto & foo = m_foo.use<&C::rejected>();
#endif
   }
private:
   ScopedMember<int, void(C::*)(), &C::granted> m_foo;
};

int main()
{
   C().granted();
   return 0;
}
1
  • Yes, I kind of agree here. Its to bad there are no "per instance" static variables just like "per thread" are. But I gues that would ruin the static definition wouldnt it? Jul 25, 2015 at 20:35
-2

Well, if you want a variable to be different from thread to thread, that variable should not be static. It's looses the point of a static variable, which is, by definition, a variable that:

  1. It's shared by all objects of that class.
  2. It does not need an class instance (object) to be accessed.

The question you're asking it's not a "coding problem", but an architectural one. I don't know what kind of system/app you're developing, maybe you need to approach your problem in a different way.

Ask yourself this questions:

  • Why do I need threads?
  • Why do I need this variable to be static?
  • What information do I need to share between threads and what information I don't want to share?

If you are more specific, maybe I can give you a more specific answer/approach.

14
  • Well, I do want a variable that is specific for each instance of a class (so thread as well). I also need it to be not local, because it is used in a method that is called in a for loop. I Could use a general member variable for that, but that variable is used only in that specific method so I dont need it outside. Thats why static for each thread. Jul 24, 2015 at 12:42
  • So the answer given by @Pumkko is the best one you can get, although conceptually/theoretical wrong. Jul 24, 2015 at 12:49
  • thread_local was only introduced in C++11, which means that your program has no retro-compatibility (which may or may not be an issue). But the main point here is that static variables are allocated on the call stack; objects are dynamically allocated in heap memory. Check static variables wikipedia article and thread local storage for more information Jul 24, 2015 at 12:57
  • I read my answer I noted I didn't answer the question itself. So, simplifying: you want a static variable to have different values from object to object, which is exactly the opposite purpose of static member variables (they are shared by all objects of that class). Jul 24, 2015 at 13:03
  • 4
    I know how this works. Thats why I used this mechanism. I can achieve 2 thigs that i want: 1. Local scope 2. global lifetime. Jul 24, 2015 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.