问题
How to implement in following OpenMP code using C# Parallel.For
OpenMP Code
#pragma omp parallel
{
float[] data = new float[1000];
#pragma omp for
for(int i = 0; i < 500; i++)
{
for(int j = 0; j < 1000; j++)
{
data[j] =100;
// do some computation using data
}
}
}
I also tried the following but it was not exactly what OpenMP code did. In the openMP code, it was allocating Memory per thread and performs the nested loop computation. Whereas the code below, actually allocates memory for each i, rather than per thread and performs the computation.
Parallel.For(0, 500, i =>
{
float[] data = new float[1000];
for(int j = 0; j < 1000; j++)
{
data[j] =100;
// do some computation using data
}
});
回答1:
Parallel.For
provides several overloads that allow one to store per-thread state variables. One of them is (fully described here):
public static ParallelLoopResult For<TLocal>(
int fromInclusive,
int toExclusive,
Func<TLocal> localInit,
Func<int, ParallelLoopState, TLocal, TLocal> body,
Action<TLocal> localFinally
)
TLocal
could be any type, e.g. float[]
in your case, and the localInit()
function is called once per thread to initialise an instance of that type in the local storage of the thread, which instance then gets passed to the body. The body
function should then return the state and it will be passed to the next iteration and so on.
Your code should look something like this:
Parallel.For<float[]>(0, 500,
() => new float[1000],
(i, loop, data) =>
{
for(int j = 0; j < 1000; j++)
{
data[j] = 100;
// do some computation using data
}
return data;
},
(data) => {}
);
Microsoft provides an example of doing this here.
来源:https://stackoverflow.com/questions/19305674/how-to-implement-openmp-multiple-level-code-using-c-sharp-parallel-for