我有一些線程計數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 。
但我描述的方式沒有工作。誰能幫忙?
什麼是指針? – mowwwalker 2012-03-25 07:52:29
指針和不安全代碼的使用是錯誤的。傳遞數組本身而不是IntPtr並像往常一樣索引數組。 – SimpleVar 2012-03-25 07:55:38
你太過於複雜。你不需要指針來填充數組。 – Steven 2012-03-25 07:57:53