簡體   English   中英

在 OpenMP 中共享作用域變量

[英]Share scoped variable in OpenMP

我正在使用 OpenMP,並希望在線程之間共享在作用域塊內聲明的變量。 這是我正在做的事情的總體思路:

#pragma omp parallel
{
    // ...parallel code...
    {
        uint8_t* pixels;
        int pitch;
#pragma omp barrier
#pragma omp master
        {
            // SDL video code must be run in main thread
            SDL_LockTexture(renderTexture.get(), nullptr, (void**)&pixels, &pitch);
        }
#pragma omp barrier
        // parallel code that reads `pixels` and `pitch` and writes to texture
#pragma omp barrier
#pragma omp master
        {
            // Once done, main thread must do SDL call again (this will upload texture to GPU)
            SDL_UnlockTexture(renderTexture.get());
        }
    }
}

當按原樣編譯時, pixelspitch將是線程私有的,並且僅在主線程中設置,從而導致段錯誤。 有沒有辦法在不增加 scope (在#pragma omp parallel之前聲明它們)或不必要地加入和重新創建線程(離開並行化部分並進入另一個#pragma omp parallel塊)的情況下共享這些變量?

解決此問題的一種方法是使用OpenMP 任務 這是一個例子:

#pragma omp parallel
{
    // ...parallel code...

    // May not be needed
    #pragma omp barrier

    #pragma omp master
    {
        uint8_t* pixels;
        int pitch;

        // SDL video code must be run in main thread
        SDL_LockTexture(renderTexture.get(), nullptr, (void**)&pixels, &pitch);

        // Note that the variables are firstprivate by default for taskloops  
        // and that shared variables must be explicitly listed as shared here
        // (as opposed to an omp for).
        #pragma omp taskloop collapse(2) firstprivate(pixels, pitch)
        for(int y=0 ; y<height ; ++y)
        {
            for(int x=0 ; x<width ; ++x)
            {
                // Code reading `pixels` and `pitch` and writing into texture
            }
        }

        // Once done, main thread must do SDL call again (this will upload texture to GPU)
        SDL_UnlockTexture(renderTexture.get());
    }

    // May not be needed
    #pragma omp barrier
}

這種基於任務的實現得益於較少的同步(在多核系統上成本很高)。

另一種可能的替代方法是使用指針將私有變量的值共享給其他線程。 但是,這種方法需要在並行部分之外聲明一些共享變量,這在您的情況下可能是不可能的。

暫無
暫無

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

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