How to define local local static variables of type thread?

How to define local static variables (which support its value between function calls) that are not used for different threads?

I am looking for an answer in both C and C ++

+18
c ++ c multithreading static thread-safety
Sep 30 '11 at 6:20
source share
6 answers

on Windows using the Windows API: TlsAlloc () / TlsSetValue () / TlsGetValue ()

on Windows using the built-in compiler: use _declspec (thread)

on Linux (another POSIX ???): get_thread_area () and related

+8
30 Sep '11 at 6:29
source share

Just use static and __thread in your function.

Example:

int test(void) { static __thread a; return a++; } 
+8
Sep 30 2018-11-11T00:
source share

There is no model for streams or the same in the current C standard, so you cannot get an answer.

The utility provided by POSIX for this is pthread_[gs]etspecific .

The next version of the C standard adds streams and has the concept of local stream storage.

+2
Sep 30 '11 at 6:26
source share

You can also use the addition of local C ++ 11 stream storage if you have access to C ++ 11.

+2
Sep 30 '11 at 12:32
source share

You can create your own private stream storage as a single point for each stream identifier. Something like that:

 struct ThreadLocalStorage { ThreadLocalStorage() { // initialization here } int my_static_variable_1; // more variables }; class StorageManager { std::map<int, ThreadLocalStorage *> m_storages; ~StorageManager() { // storage cleanup std::map<int, ThreadLocalStorage *>::iterator it; for(it = m_storages.begin(); it != m_storages.end(); ++it) delete it->second; } ThreadLocalStorage * getStorage() { int thread_id = GetThreadId(); if(m_storages.find(thread_id) == m_storages.end()) { m_storages[thread_id] = new ThreadLocalStorage; } return m_storages[thread_id]; } public: static ThreadLocalStorage * threadLocalStorage() { static StorageManager instance; return instance.getStorage(); } }; 

GetThreadId (); It is a platform-specific function for determining the caller ID. Something like that:

 int GetThreadId() { int id; #ifdef linux id = (int)gettid(); #else // windows id = (int)GetCurrentThreadId(); #endif return id; } 

Now, as part of the stream function, you can use local storage:

 void threadFunction(void*) { StorageManager::threadLocalStorage()->my_static_variable_1 = 5; //every thread will have // his own instance of local storage. } 
+1
Sep 30 '11 at 7:19
source share

You can create a data structure allocated from the heap for each thread.

Example:

 struct ThreadLocal { int var1; float var2; //etc.. } 
-2
Sep 30 '11 at 6:28
source share



All Articles