Vous pouvez faire votre propre fil spécifique de stockage local singleton par ID de fil. Quelque chose comme ceci:
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(); est une fonction spécifique à la plateforme pour déterminer l'identifiant du thread de l'appelant. Quelque chose comme ceci:
int GetThreadId()
{
int id;
#ifdef linux
id = (int)gettid();
#else // windows
id = (int)GetCurrentThreadId();
#endif
return id;
}
maintenant, dans une fonction de fil que vous pouvez utiliser est le stockage local:
void threadFunction(void*)
{
StorageManager::threadLocalStorage()->my_static_variable_1 = 5; //every thread will have
// his own instance of local storage.
}
Quel système d'exploitation utilisez-vous? TLS n'est pas portable entre unixen et Windows. – bdonlan
C++ 11 introduit une autre durée de stockage appelée ['thread_local'] (http://en.cppreference.com/w/cpp/language/storage_duration). Essayez de l'utiliser. – Nawaz
OS est Windows ... –