[英]How to parallelize a for loop
I try to parallelize this for in for loop because I want to use in code with parallel stream in java . 我尝试将此for for循环 并行化 ,因为我想在Java中使用具有并行流的代码。 The problem is.. Every time I've try to do this I don't get the entire result.
问题是..每次尝试执行此操作时,我都无法获得全部结果。 I mean... this code should rotate an image with some angle, but if I'm doing a parallelize I will receive just half of image rotated.
我的意思是……此代码应将图像旋转一定角度,但是如果执行并行化处理,我将仅收到旋转图像的一半。
One issue could be the a, b, xx, yy variables being declared outside the for loop. 一个问题可能是a,b,xx,yy变量在for循环外声明。 It could be that different (interleaved) iterations overwrite the values of these variables.
可能是不同的(交错的)迭代覆盖了这些变量的值。 For instance,
例如,
I think there are some problems with this implementation. 我认为此实现存在一些问题。
1) each of your thread from parallelstream is going to override the ImageIo.write the other thread did. 1)您来自parallelstream的每个线程都将覆盖ImageIo.write其他线程所做的。
2) Also, forEach is unordered so you don't know which half will happen first. 2)而且,forEach是无序的,因此您不知道哪一半先发生。
I think your better bet is to use collect
method from the Stream API. 我认为您最好的选择是使用Stream API中的
collect
方法。 I can give some code if you need help. 如果您需要帮助,我可以提供一些代码。 However if you give me a testable code in your question, I will write the parallel collect operation.
但是,如果您在问题中给我一个可测试的代码,我将编写并行收集操作。 Else, all the best.
否则,一切顺利。
Edit 编辑
I did some checking and found that your rotateImage
is the culprit. 我做了一些检查,发现您的
rotateImage
是元凶。 The problem has nothing to do with parallelStream
. 这个问题与
parallelStream
无关。 There is lot of transformation required for each point (x1,y1) and it is bit too much for me to code right now. 每个点(x1,y1)都需要进行大量转换,现在对我来说很难编码。 Your algorithm should be taking care of following:
您的算法应注意以下事项:
Once you have taken care of all this translations and rotations for each pixel along with the buffer's height and width, in rotateImage function, I think you can just call the parallelStream function on your locations stream and you won't have issues. 一旦您处理了每个像素的所有平移和旋转以及缓冲区的高度和宽度后,在rotateImage函数中,我认为您只需在位置流上调用parallelStream函数,就不会有问题。
Some libraries like OpenGL can make this very easier for you. 诸如OpenGL之类的某些库可以使您更轻松地完成此工作。 They take care of rotating and translating each pixel vector around the center with rotation vector and translation vector.
他们负责使用旋转矢量和平移矢量围绕中心旋转和平移每个像素矢量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.