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

本文关键字:数组 2d 线程 为什么 | 更新日期: 2023-09-27 18:02:12

我对c#中的线程非常陌生,我不明白为什么我的线程在执行过程中停止了。

我在Unity3d中建立了自己的地形解决方案。地形是由大块组成的。每个块的网格应该在一个线程上更新,这样在游戏过程中就不会有任何明显的帧丢失。

我创建了一个线程调用UpdateChunkMeshData与一些参数。任何时候我试图访问我的二维数组块在线程中它停止。为什么会发生这种情况?

代码的缩短版本:

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

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

数组不是线程安全的。更多信息:数组和线程安全访问。

如果你在你的Chunk中有一些锁,你可能会面临死锁。

为什么要用这么多线程?我想这可能是更好的创建一个线程和更新所有的块在一个线程。