为什么线程在获得2d数组值后停止?

时间:2015-07-12 05:48:46

标签: c# multithreading unity3d mesh terrain

我对C#中的线程非常陌生,我无法弄清楚为什么我的线程在执行过程中停止了。

我在Unity3d中构建了自己的地形解决方案。地形由块组成。应该在线程上更新每个块的网格,以便在播放期间不会出现任何明显的帧丢失。

我创建了一个使用一些参数调用UpdateChunkMeshData的线程。每当我尝试在线程中访问我的2d数组块时它就会停止。为什么会这样?

代码的简短版本:

public Chunk[,] Chunks;


public class Chunk
{
    public GameObject gameObject;
    public float[,] Heights;
    public int Resolution;

    public bool NeedsToUpdate;
    public bool Busy;
    public bool MeshReady;

}


for (int x = 0; x < ChunkCountX; x++)
{
    for (int y = 0; y < ChunkCountY; y++)
    {

        Thread thread = new Thread(() => {
                                Debug.Log("Starting thread for chunk " + ChunkIndexX + ", " + ChunkIndexY);
                                UpdateChunkMeshData(x, y, Resolution, false, false, false, false);
                                Debug.Log("Finished thread for chunk " + ChunkIndexX + ", " + ChunkIndexY);
                               });


        thread.Start();
    }
}


private void UpdateChunkMeshData(int ChunkX, int ChunkY, int someOtherParams)
{
    Debug.Log("Thread started fine");

    // As soon as I try to access any of the chunks in the array the thread stops. I don't get any errors either.
    Debug.Log(Chunk[ChunkX, ChunkY].Heights[x, y]);

    Debug.Log("Thread doesn't print this");
}

1 个答案:

答案 0 :(得分:2)

数组不是线程安全的。有关详细信息:array and safe access by threads

如果你的Chunk中有一些锁定,你可能会遇到死锁。

为什么要使用这么多线程?我想最好创建一个线程并在一个线程中更新所有块。