Transforming arrays in-place with parallel collections

守給你的承諾、 提交于 2020-01-13 09:37:06

问题


When one has an array of objects it is often desirable (e.g. for performance reasons) to update (replace) some of the objects in place. For example, if you have an array of integers, you might want to replace the negative integers with positive ones:

// Faster for primitives
var i = 0
while (i < a.length) {
  if (a(i) < 0) a(i) = -a(i)
  i += 1
}

// Fine for objects, often okay for primitives
for (i <- a.indices) if (a(i) < 0) a(i) = -a(i)

What is the canonical way to perform a modification like this using the parallel collections library?


回答1:


As far as parallel arrays are considered - it's an oversight. A parallel transform for parallel arrays will probably be included in the next release.

You can, however, do it using a parallel range:

for (i <- (0 until a.length).par) a(i) = computeSomething(i)

Note that not all mutable collections are modifiable in place this way. In general, if you wish to modify something in place, you have to make sure it's properly synchronized. This is not a problem for arrays in this case, since different indices will modify different array elements (and the changes are visible to the caller at the end, since the completion of a parallel operation guarantees that all writes become visible to the caller).




回答2:


Sequential mutable collections have methods like transform which work in-place.

Parallel mutable collections lack these methods, but I'm not sure there is a reason behind it or if it is just an oversight.

My answer is that you're currently out of luck, but you could write it yourself of course.

Maybe it would make sense filing a ticket after this has been discussed a bit more?




回答3:


How about creating a parallel collection that holds the indices into the array to transform and then run foreach to mutate one cell in an array, given the index.

That way you also have more control and it is possible to make four workers, that work on the four quarters of an array. Because simply flipping one single integer sign is probably not enough work to justify a parallel computation.



来源:https://stackoverflow.com/questions/6141744/transforming-arrays-in-place-with-parallel-collections

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