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

限于喜欢 提交于 2019-12-12 17:58:52

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/41068201/if-i-make-a-piece-of-code-in-which-each-thread-modifies-completely-different-par

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!