Axis
Axis

Reputation: 846

Multithreading Arrays

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 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.

But the way I have described up there does not work. Can anyone help?

Upvotes: 0

Views: 499

Answers (1)

Dmitry Reznik
Dmitry Reznik

Reputation: 6862

There's no need to use pointer arithmetic to access array in 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. Also, you don't have to use pointer arithmetic since array is already passed by reference and can be accessed by index.

Upvotes: 1

Related Questions