C ++: OpenMP shared memory protection

If I use a shared variable, say double, to calculate some amount of program execution. Will it be vulnerable to unstable operations anyway? I mean, is it possible that more than one core will access this variable asynchronously and cause erratic results?

For example: this is a global variable:

double totalTime = 0;

and in each core the command is called:

totalTime += elapsedTime;

This last operation / statement is executed, taking the value totalTime, put it in the CPU register, and then add it. I can imagine that more than one core will take the same value at the same moment, and then add a new elapsedTime, and then the value stored in totalTime will be overwritten with the wrong value due to the delay. Is it possible? and how can i solve this?

Thank.

+5
source share
1 answer

Obviously, this operation is not thread safe, because, as you mentioned yourself, it includes several assembler instructions. In fact, openMP even has a special directive for this kind of operation.

You will need a pragma atomicto make this, well, “atomic”:

#pragma omp atomic
totalTime += elapsedTime;

, atomic , , , , ..

, , critical:

#pragma omp critical
{
    // atomic sequence of instructions
}

: "snemarch": totalTime , reduction :

double totalTime = 0;

#pragma omp parallel for reduction(+:totalTime)
for(...)
{
    ...
    totalTime += elapsedTime;
}

totalTime elapsedTime .

+4

All Articles