如何定义线程局部的局部静态变量

How to define thread-local local static variables?

本文关键字:局部 静态 变量 线程局 何定义 定义      更新时间:2023-10-16

如何定义不同线程之间不共享的局部静态变量(在函数调用之间保持其值)?

我正在寻找C和c++的答案

在Windows上使用Windows API: TlsAlloc()/TlsSetValue()/TlsGetValue()

在Windows上使用编译器:use _declspec(thread)

在Linux(其他POSIX??): get_thread_area()和相关

在你的函数中使用static和__thread。

的例子:

int test(void)
{
        static __thread a;
        return a++;
}

当前的C标准没有线程或类似的模型,因此您无法在那里得到答案。

POSIX预见的实用程序是pthread_[gs]etspecific

下一个版本的C标准增加了线程,并有了线程本地存储的概念。

如果您可以访问c++ 11,您也可以使用c++ 11线程本地存储。

您可以将自己的线程特定的本地存储设置为每个线程ID的单个存储。像这样:

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 ();是特定于平台的函数,用于确定调用者的线程id。像这样:

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

现在,在一个线程函数中,你可以使用它的本地存储:

void threadFunction(void*)
{
  StorageManager::threadLocalStorage()->my_static_variable_1 = 5; //every thread will have
                                                           // his own instance of local storage.
}