Alex Rivera | Logout

C++: how to create thread local/global variable

Asked 2010-09-03T15:34:17.050
10

in this code:

int foo() {
   static int x;
}

is the x global to all threads or local in each thread? Or does that depends on a compiler flag and/or the compiler, so I cannot really know what it is from the code?

Several questions (all of them independent from compiler and compiler flags and OS):

  1. How can I create a static variable which is global to all threads?
  2. How can I create a static variable which is local to each thread?
  3. How can I create a global variable which is global to all threads?
  4. How can I create a global variable which is local to each thread?

I guess that this is not in C++ itself. (Is it in C++0x?) Some Boost lib which can do this?

Edit
Report

1 Answer

1

You'd have to be using some kind of cross platform threading library (since you mentioned OS independence), but given pthreads you could do.

template <T>
class myVarStorage
{
    static std::map<int, T> store_;
public:
    myVarStorage();
    T getVar();
    void setVar(T);
}

template <T> void myVarStorage::setVar<T>(T var)
{
     store_[static_cast<int>pthread_self()] = var;
}

template <T> T myVarStorage::getVar()
{
     return store_[static_cast<int>pthread_self()]; //throws exception 
}

I'm sure the code has errors in it and should be treated as pseudo-code, since I'm a pseudo-programmer when it comes to C++. :)

answered 2010-09-03T16:12:18.103

Your Answer