簡體   English   中英

如何定義線程局部局部靜態變量?

[英]How to define thread-local local static variables?

如何定義不在不同線程之間共享的局部靜態變量(在函數調用之間保持其值)?

我正在尋找 C 和 C++ 的答案

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

在 Windows 上使用編譯器內在:使用_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();
    }
};

獲取線程 ID(); 是一個特定於平台的函數,用於確定調用者的線程 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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM