[英]Multithreading Arrays
I have some Thread count pCount and I have some float[] array. 我有一些线程计数pCount和一些float []数组。 I want to get a pointer to the array and then based on pCount create that many threads and fill the array with data. 我想获得一个指向数组的指针,然后基于pCount创建那么多线程,并用数据填充数组。
fixed (float* pointer = array)
{
IntPtr fPtr = new IntPtr(pointer);
for (int i = 0; i < pCount; i++)
{
Thread t = new Thread(() => ThreadMethod(fPtr, blockWidth, blockHeight, xIndex)));
t.Start();
}
}
private unsafe void ThreadMethod(IntPtr p, int blockWidth, int blockHeight, int startX)
{
Random RandomGenerator = new Random();
for (int x = startX; x < startX + blockWidth * blockHeight; x++)
{
((float*)p)[x] = ((float)(RandomGenerator.NextDouble()) - 0.5f) * 2.0f;
}
}
So if the array was 1000x1000 and I have 4 threads I want thread 1 to fill data from 0 - 250 then thread 2 from 250 - 500, thread 3 from 500 - 750 and thread 4 from 750 - 1000. 因此,如果数组是1000x1000,并且我有4个线程,我希望线程1填充0-250的数据,然后希望线程2填充250-500的线程,线程3填充500-750的线程,并且线程4填充750-1000的线程。
But the way I have described up there does not work. 但是我在那里描述的方式行不通。 Can anyone help? 有人可以帮忙吗?
There's no need to use pointer arithmetic to access array in C#. 不需要使用指针算法来访问C#中的数组。 Here's a simplified example of how it can be done: 这是一个简化的示例,它是如何完成的:
public void ParalellizeArrayFill(int threadCount, float[] array)
{
if (array == null || array.Length == 0)
throw new ArgumentException("Array cannot be empty");
if (threadCount <= 1)
throw new ArgumentException("Thread count should be bigger than 1");
int itemsPerThread = array.Length / threadCount;
for (int i = 0; i < threadCount; i++)
{
Thread thread = new Thread( (state) => FillArray(array, i*itemsPerThread, itemsPerThread));
thread.Start();
}
}
private void FillArray(float[] array, int startIndex, int count)
{
for (int i = startIndex; i < startIndex + count; i++)
{
// init value
array[i] = value;
}
}
There are a few caveats to be aware of. 有一些注意事项。 First of all, your division may not divide equally (500/3 for example), so you have to handle this case. 首先,您的划分可能不会平均分配(例如500/3),因此您必须处理这种情况。 Also, you don't have to use pointer arithmetic since array is already passed by reference and can be accessed by index. 另外,由于数组已经通过引用传递并且可以通过索引访问,因此您不必使用指针算法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.