我有一个进程在随机位置上运行大量任务,Array
并希望通过使用多线程来加快速度.
它本质上做的是随机化"阵列"中的位置,检查其近似环境的值,并在满足一些特定条件时改变随机位置值.
是否有可能运行像
Parallel.For(0, n, s => { });
循环而不是下面显示的while代码块来优化这个函数,一个代码块怎么样呢?
我一直在考虑为所选元素使用一些"忙"属性,但这实际上使得问题可能需要更加复杂.
public void doStuffTothisArray(ref int[,,] Array, ref IGenerator randomGenerator, int loops) { int cc = 0; int sw = 0; do { if (doStuffOnRandomPositions(ref Array, ref randomGenerator)) sw++; //if stuff was made counter if ((cc % (loops / 10)) == 0) Console.Write("{0} % \t", (cc / (loops / 10)) * 10); //some loading info cc++; //count iterations } while (cc < loops); Console.WriteLine("Stuff altered in {0} iterations: {1}", loops, sw); }
发布编辑:
划分阵列并分配工作会破坏阵列的动态,因为它需要是一个完整的系统.
这是dostuff的原型..()
public static bool doStuffOnRandomPositions(ref lattice A, ref IGenerator rr) { position firstPos = new position(rr.Next(0, A.n_size),rr.Next(0, A.n_size),rr.Next(0, A.n_size)); position secondPos = randomNeighbour(ref A, firstPos, ref rr); //checks the closest 3d neighbours indexer the lattice //Console.WriteLine("first:[{0},{1},{2}]\nsecond:[{3},{4},{5}]\n", firstPos.x, firstPos.y, firstPos.z, secondPos.x, secondPos.y, secondPos.z); // get values at coordinates bool first = A.latticeArray[firstPos.x, firstPos.y, firstPos.z]; bool second = A.latticeArray[secondPos.x,secondPos.y,secondPos.z]; if (first == second) //don't bother if they are equal states return false; // checks the energies in surroundings for an eventual spin switch int surrBefore = surroundCheck(ref A, firstPos, first) ; // - surroundCheck(ref A, secondPos, second)); int surrAfter = surroundCheck(ref A, firstPos, !first) ; // - surroundCheck(ref A, secondPos, !second)); if (surrAfter < surrBefore) //switch spin states if lower total energy { A.latticeArray[firstPos.x, firstPos.y, firstPos.z] = !first; A.latticeArray[secondPos.x, secondPos.y, secondPos.z] = !second; return true; } else if ((surrAfter == surrBefore) & latticeDistribution(ref rr)) //TEMPORARY { A.latticeArray[firstPos.x, firstPos.y, firstPos.z] = !first; //TEMPORARY A.latticeArray[secondPos.x, secondPos.y, secondPos.z] = !second; //TEMPORARY return true; } else return false; } //FIX SWITCH PROBABILITIES
在这里,晶格类应该表示包含其属性的"数组".由于我对c#方法的经验不足,示例解决方案代码非常感谢.
如果您的操作范围限定为不相交的元素范围(如1-10,25-40,100-123),则可以不对各个元素并行运行,而是在不同的范围上运行操作.如果在操作正在进行时不重新分配阵列,则不需要任何其他同步.
如果操作更改随机元素,则必须处理正确的同步,并且可能无法获得在多个线程上运行代码的任何好处.