How to define local static variables (that keeps its value between function calls) that are not shared among different threads?
I am looking for an answer both in C
You can make your own thread specific local storage as singleton per thread ID. Something like this:
struct ThreadLocalStorage
{
ThreadLocalStorage()
{
// initialization here
}
int my_static_variable_1;
// more variables
};
class StorageManager
{
std::map m_storages;
~StorageManager()
{ // storage cleanup
std::map::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(); is a platform specific function for determining caller's thread id. Something like this:
int GetThreadId()
{
int id;
#ifdef linux
id = (int)gettid();
#else // windows
id = (int)GetCurrentThreadId();
#endif
return id;
}
Now, within a thread function you can use it's local storage:
void threadFunction(void*)
{
StorageManager::threadLocalStorage()->my_static_variable_1 = 5; //every thread will have
// his own instance of local storage.
}