c++ - 使非 const 对象成员函数在 openMP 中可用

标签 c++ openmp

我想并行化一些循环,并在代码的其他部分广泛使用 openMP。我想在一个循环中使用一个对象,它有一些后备存储(应该跨线程共享)和一些状态(应该对每个线程私有(private))。

想象一下:

class P {
    public:
        // fills storage with 0, 1, 2...
        P(size_t something) {
            for(size_t i = 0; i < something; i++)
                m_storage.push_back(i);
        }

        // finds the closest value in m_storage to probe
        // the algorithm is a stupid dummy, but gets the point across
        float findClosest(float probe) {
            m_state = std::numeric_limits<float>::max();
            auto closest = std::numeric_limits<float>::quiet_NaN();

            for(const auto x: m_storage)
                if(m_state > probe - x) {
                    closest = x;
                    m_state = probe - x;
                }

             return closest;
        }

    private:
        std::vector<float> m_storage;
        float m_state;
}

// sequential access
int main(){
    P p = new P(100);
    std::vector<float> results(5);
    for(size_t i = 0; i<5; i++) {
        results[i] = p.findClosest(i);
    }
}

// parallel access with copy => p.m_storage is copied
int main(){
    P p = new P(100);
    std::vector<float> results(5);
#pragma omp parallel for firstprivate(p)
    for(size_t i = 0; i<5; i++) {
        results[i] = p.findClosest(i);
    }
}

// parallel access with share => p.m_state is altered by multiple threads
int main(){
    P p = new P(100);
    std::vector<float> results(5);
#pragma omp parallel for firstprivate(p)
    for(size_t i = 0; i<5; i++) {
        results[i] = p.findClosest(i);
    }
}

因此要么我浪费了大量内存和缓存空间,要么由于共享变量而导致实现中断。

我想我不能将对象的一部分标记为共享,将其他部分标记为私有(private)或类似的东西。对象比较复杂,状态用在不同的地方。有没有什么神奇的方法可以让对象共享其存储空间,但每个对象都有状态?

例如像

[...]
    private:
#pragma omp parallel shared
        std::vector<float> m_storage;
#pragma omp parallel private
        float m_state;

最佳答案

将您的数据分为两类:一类包含要在线程之间共享的所有数据,另一类包含每个线程的私有(private)数据。每线程类将包含一个 const 指针或对公共(public)数据的引用(const 因为您不想对其进行更改)。

类似于:

class common {
public:
    std::vector<float> m_storage;
    // ...
};

class private_data {
public:
    private_data(const common *cstorage): storage(cstorage) { }
    const common *storage;
    float findClosest(float probe) {
        // ...
    }
};

common 类将有一个实例,传递给所有 private_data 类。

关于c++ - 使非 const 对象成员函数在 openMP 中可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59721512/

相关文章:

c++ - openmp parallel for with non-PODs

c++ - 扫描快速排序拆分

C++如何对齐文件的每一行?

c - OPENMP - 带前提条件的并行化 Schwarz 算法

c - for 循环上的多个 pragma 指令(C 和 VS 2013)

c++ - Visual Studio 错误 D8016 : '/ZI' and '/Gy' command-line options are incompatible

c++ - 推力 set_intersection 是如何工作的?

c++ - 如何在 CWinApp 中获取 WM_POWERBROADCAST 消息?

c++ - 获取 boost::multi_index 容器元素的等级

c++ - 在 Visual Studio 的 Python 中调用 C++ 项目 main()?