在OpenMP并行区域中使用向量push_back是否安全?

时间:2015-11-06 04:20:20

标签: c++ openmp

我知道我不应该在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);
                }
            }
        }

1 个答案:

答案 0 :(得分:0)

OpenMP标准在section 2.7.1附近说:

  

在循环区域内执行的throw必须导致执行恢复   在循环区域的相同迭代内,和相同的线程   抛出异常必须抓住它。

push_back()try - catch结构封装在critical区域内,可以使代码安全。