在性能关键的并行代码中,我有一个向量,其元素是:
目前,我预先计算了向量的所有可能值,因此竞争条件不应成为问题.为了提高性能,我正在考虑创建一个惰性向量,这样代码只在请求向量元素时执行计算.在并行区域中,可能会发生多个线程同时请求并且可能同时计算相同元素的情况.我如何处理这种可能的竞争条件?
下面是我想要实现的一个例子.它在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)