2012-03-25 40 views
0

我有一些線程計數pCount,我有一些float []數組。我想獲得一個指向數組的指針,然後基於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; 
    } 
} 

因此,如果陣列是1000×1000,我有4個線程我想線程1從0填補數據 - 250那麼線程2 250 - 500,線程3從500 - 750和螺紋4 750 - 1000 。

但我描述的方式沒有工作。誰能幫忙?

+1

什麼是指針? – mowwwalker 2012-03-25 07:52:29

+1

指針和不安全代碼的使用是錯誤的。傳遞數組本身而不是IntPtr並像往常一樣索引數組。 – SimpleVar 2012-03-25 07:55:38

+0

你太過於複雜。你不需要指針來填充數組。 – Steven 2012-03-25 07:57:53

回答

1

沒有必要使用指針運算來訪問C#中的數組。這裏有一個簡單的例子:

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; 
    } 
} 

有幾點需要注意的注意事項。首先,你的部門不可以平分(例如500/3),所以你必須處理這個案子。此外,您不必使用指針算術,因爲數組已經通過引用傳遞並且可以通過索引訪問。

+0

這不起作用。該數組只是空的。它永遠不會被填滿。 – Axis 2012-03-25 18:35:29

+0

你能指定你是怎麼做的嗎?我剛剛複製粘貼到視覺工作室,增加了隨機數值的生成,它的工作。 – 2012-03-25 18:48:29

+0

所以我剛剛複製了你發佈的確切代碼,並試圖在一個20的數組和4的線程數上運行它。有些事情出錯了,我似乎無法修復。 FillArray方法會拋出一個異常,因爲數組[i]超出了界限,因爲startIndex = 20。這是不可能的,因爲只有4個線程被創建,並且起始索引應該是0,5,10和15,但不知何故它會得到20 。 有任何想法嗎?這是我改變了唯一的東西float [] array = new float [20]; \t \t \t ParalellizeArrayFill(4,array);和array [i] =(float)random.NextDouble()* 10; – Axis 2012-03-25 19:14:47