簡體   English   中英

在OpenMP中重置線程局部變量

[英]Reset thread-local variables in OpenMP

我需要一種一致的方法來重置我的程序創建的所有線程局部變量。 問題在於線程局部數據是在與使用它們的位置不同的地方創建的。

我的課程大綱如下:

struct data_t { /* ... */ };

// 1. Function that fetches the "global" thread-local data
data_t& GetData()
{
    static data_t *d = NULL;
    #pragma omp threadprivate(d); // !!!

    if (!d) { d = new data_t(); }

    return *d;
}

// 2 example function that uses the data
void user(int *elements, int num, int *output)
{
    #pragma omp parallel for shared(elements, output) if (num > 1000)
    for (int i = 0; i < num; ++i)
    {
        // computation is a heavy calculation, on memoized data
        computation(GetData()); 
    }
}

現在,我的問題是我需要一個重置數據的函數,即必須考慮創建的每個線程局部對象。

現在,我的解決方案是使用並行區域,希望使用與“parallel for”相同或更多的線程,以便每個對象都“迭代”通過:

void ClearThreadLocalData()
{
    #pragma omp parallel
    {
        // assuming data_t has a "clear()" method
        GetData().clear();
    }
}

是否有更慣用/安全的方法來實現ClearThreadLocalData()

您可以為數據創建和使用全局版本號。 每次需要清除現有緩存時增加它。 然后修改GetData以檢查版本號是否存在現有數據對象,丟棄現有數據對象並創建新數據對象(如果已過期)。 (如果可以修改類,則分配的data_t對象的版本號可以存儲在data_t否則可以存儲在第二個線程局部變量中。)你最終會得到像

static int dataVersion;

data_t& GetData()
{
    static data_t *d = NULL;
    #pragma omp threadprivate(d); // !!!

    if (d && d->myDataVersion != dataVersion) {
        delete d;
        d = nullptr;
    }
    if (!d) { 
        d = new data_t();
        d->myDataVersion = dataVersion;
    }

    return *d;
}

這不依賴於data_t是否存在Clear方法,但是如果你有一個方法,則通過調用Clear來替換delete-and-reset。 我正在使用d = nullptr來避免重復調用new data_t()

如果要避免全局變量,全局dataVersion可以是dataVersion的靜態成員, data_t如果需要它可以是原子的,盡管GetData需要更改來處理它。

當需要重置數據時,只需更改全局版本號:

++dataVersion;

暫無
暫無

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

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