簡體   English   中英

在OpenMP並行區域中使用向量push_back是否安全?

[英]Is it safe to use vector push_back in an OpenMP parallel region?

我知道我不應該在openmp並行區域內引發任何未捕獲的異常。 因此,我認為以下循環並不安全,因為vector的push_back函數可能導致內存重新分配,從而有可能引發異常。

我查閱了文檔,並說If a reallocation happens, the strong guarantee is also given if the type of the elements is either copyable or no-throw moveable.

那我的代碼安全嗎? Star是包含浮點數的基本數據結構。

        std::vector<Star> stars;

        #pragma omp parallel for
        for(size_t i = 1; i < (gimg.height() - 1) * 2; i++)
        {
            float i_ = i / 2.0f;

            for(float j = 1; j < gimg.width() - 1; j += 0.5f)
            {
                //a b c
                //d e f
                //g h k

                quantum_t e = gimg.bilinear(j, i_);

                quantum_t a = gimg.bilinear(j - 1, i_ - 1);
                if(a >= e) continue;

                quantum_t b = gimg.bilinear(j, i_ - 1);
                if(b >= e) continue;

                quantum_t c = gimg.bilinear(j + 1, i_ + 1);
                if(c >= e) continue;

                quantum_t d = gimg.bilinear(j - 1, i_);
                if(d >= e) continue;

                quantum_t f = gimg.bilinear(j + 1, i_);
                if(f >= e) continue;

                quantum_t g = gimg.bilinear(j - 1, i_ + 1);
                if(g >= e) continue;

                quantum_t h = gimg.bilinear(j, i_ + 1); 
                if(h >= e) continue;

                quantum_t k = gimg.bilinear(j + 1, i_ + 1);
                if(k >= e) continue;

                bool ismax = d >= a && d >= g && h >= g && h >= k && f >= k && f >= c && b >= c && b >= a;

                if(ismax)
                {
                    Star s;
                    s.brightness = e;
                    s.location = Point<float>(j, i_);

                    #pragma omp critical
                    stars.push_back(s);
                }
            }
        }

OpenMP標准在第2.7.1節結尾處說:

在循環區域內執行的throw必須使執行在循環區域的同一迭代中恢復,並且引發異常的同一線程必須捕獲該異常。

因此,將push_back()構造本身包含在try - catch構造中,使其位於critical區域內,應該可以確保您的代碼安全。

暫無
暫無

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

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