Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
711 views
in Technique[技术] by (71.8m points)

c++ - If I make a piece of code in which each thread modifies completely different parts of an array, will that maintain cache coherency?

So I am making some parallel code using OpenMP (but this question should be reasonably applicable to other frameworks), in which I have an array of objects:

std::vector<Body> bodies;

And then I do a little parallel loop to do some things to the bodies. At the start of this parallel section, a team of threads is set up to execute the loop individually. The loop basically uses the values of foo on every Body (apart from the one in question) to update the value of bar on the body in question. So essentially no writes are being done to the values of foo on each body, and the only reads being done on bar are localised to the thread controlling that particular body; in pseudocode, it looks like this:

//create team of threads, and then this section is executed by each thread separately
for each Body i
    for each Body j =/= i
        i.bar += (j.foo * 2);
    end for
end for

My question is whether this will, as I think it should, maintain the coherency of the cache? Because as far as I see it, none of the threads are reaching for things that are being edited by the other threads, so it should be safe, I feel. But This is quite an important point in the report that I need to write on this, so I want to be sure.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The rule is you need synchronization if you have more than one thread and at least one of them is a writer and the threads are accessing the same object. If all of your threads are reading then you do not need any synchronization at all.

With an array/vector if you are writing to it but each thread is writing to its own unique section then you do not need any synchronization either as you are not accessing the same underlying objects (as long as you are not modifying the vector itself like adding or removing elements). The only hazard with this is false sharing. If two threads are working on the different parts of the array but they happen to be on the same cache line then any modification is going to dirty the cache line and both threads will be impacted. This is just a performance impact though and does not lead to undefined behavior.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...