-2

I want to have a member variable shared inside a thread ,but not shared among threads .

It behaves like a static member but it's only "global" in one thread ,it's a thread local variable .

I can think of two solutions :

First ,create a local variable in each thread ,then pass this variable as an argument to every method that uses it .(which result in coupling)

Or ,define a struct named MyStruct which contains a thread local variable and a thread ID ,then make all these MyStructs a vector ,use this vector as a static member variable .

Every time using this member variable , get thread ID first ,then find the MyStruct which has the same thread ID , if not found ,push back a new MyStruct .Erase this Mystruct before thread ends .(which is inconvenient)

Is there a simple solution ?

iouvxz
  • 89
  • 9
  • 27
  • Completely unclear what you're actually asking for, sorry. – πάντα ῥεῖ Sep 15 '15 at 00:19
  • 1
    @πάνταῥεῖ: Really? He says exactly that he wants: (1) a member variable which is (2) a static member and (3) a thread local variable. In the first two sentences. – Ben Voigt Sep 15 '15 at 00:23
  • possible duplicate of [What does the thread\_local mean in C++11?](http://stackoverflow.com/questions/11983875/what-does-the-thread-local-mean-in-c11) – 5gon12eder Sep 15 '15 at 00:25
  • @5gon12eder: Really this is the opposite. This OP already knows what a thread local variable is, and asks how to do it in C++. The other spotted a new keyword for creating thread local variables, and asks what they are. – Ben Voigt Sep 15 '15 at 00:26
  • @BenVoigt True, but I think that the answers to the other question (especially those with code) should give the OP enough information to solve the problem. No? – 5gon12eder Sep 15 '15 at 00:28
  • Well, none of the examples there are of member variables. If answers there were expanded, I think it could answer this one too. – Ben Voigt Sep 15 '15 at 01:29

1 Answers1

6

C++ supports thread local variables since C++11, using the thread_local keyword.

It can be used on static member variables.

Using the language facility designed for this is much simpler than trying to create your own. There are quite a few little details concerning initialization order and reentrancy, and then eventual destruction, that would be hard to get right without the compiler's help.

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720