小编Enz*_*ano的帖子

并行循环中的惰性向量访问

性能关键的并行代码中,我有一个向量,其元素是:

  • 计算起来非常昂贵,结果是确定性的(给定位置的元素值仅取决于位置)
  • 随机访问(通常访问次数大于或大于向量的大小)
  • 集群访问(许多访问请求相同的值)
  • 向量由不同的线程共享(竞争条件?)
  • 为避免堆碎片整理,永远不应重新创建对象,但只要可能,就可以重置和回收
  • 放置在向量中的值将由多态对象提供

目前,我预先计算了向量的所有可能值,因此竞争条件不应成为问题.为了提高性能,我正在考虑创建一个惰性向量,这样代码只在请求向量元素时执行计算.在并行区域中,可能会发生多个线程同时请求并且可能同时计算相同元素的情况.我如何处理这种可能的竞争条件?

下面是我想要实现的一个例子.它在Windows 10,Visual Studio 17下编译和运行.我使用C++ 17.

// Lazy.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <vector>
#include <iostream>
#include <stdlib.h>  
#include <chrono>
#include <math.h>
const double START_SUM = 1;
const double END_SUM = 1000;

//base object responsible for providing the values
class Evaluator
{
public:
    Evaluator() {};
    ~Evaluator() {};
    //Function with deterministic output, depending on the position
    virtual double expensiveFunction(int pos) const = 0;
};
// …
Run Code Online (Sandbox Code Playgroud)

c++ parallel-processing openmp c++17

6
推荐指数
1
解决办法
487
查看次数

标签 统计

c++ ×1

c++17 ×1

openmp ×1

parallel-processing ×1