I have some Thread count pCount and I have some float[] array. I want to get a pointer to the array and then based on pCount create that many threads and fill the array with data.
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 1000×1000 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.
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#. Here’s a simplified example of how it can be done:
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. Also, you don’t have to use pointer arithmetic since array is already passed by reference and can be accessed by index.