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

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


x is global to all threads. Always, independent of compiler and/or its flags. Independent of whether this is in C++11 or C++03. So if you declare a regular global or static local variable, it will be shared between all threads.In C++11 we will have the thread_local keyword. Until then, you can use thread_specific_ptr from Boost.Thread.


Quick partial answers;

(Is it in C++0x?)

Yes. But depends on your compiler's C++0x support too.

Some Boost lib which can do this?

Boost.Threads. See thread local storage therein.

  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?

Note that typically, static refers to duration and global refers to scope.

C++0x thread constructors are variadic: You can pass any number (and type) of arguments. All of these are available to your std::thread object.

#include <thread>int main(){    int foo = 42;    std::thread t(foo); // copies foo    std::thread s(&foo); // pass a pointer    t.join();}


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++. :)