2015-07-12 21 views
0

我很新的線程在C#中,我無法弄清楚爲什麼我的線程停在執行中。爲什麼線程在獲取2d數組值後停止?

我在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"); 
} 
+0

你確定你的'Chunks'數組被正確初始化了嗎?看起來你可能正在訪問一個不存在的數組位置,所以'Thread'終止於一個異常。 – Corey

+0

我確定它已被初始化。 –

回答

2

數組不是線程安全的。欲瞭解更多信息:array and safe access by threads

如果你在你的塊中有一些鎖定,你可能會面臨死鎖。

爲什麼你使用這麼多的線程?我想最好創建一個線程並在一個線程中更新所有的塊。

0

您應該使用「鎖定」關鍵字來同步線程。

public class Example 
{ 

    private object threadLock = new object(); 

    private void Method() 
    { 

     lock(threadLock){ ... } 

    } 
} 
+0

在更新塊函數中,我嘗試了一些鎖(塊)和鎖(塊[ChunkX,ChunkY])。虛空似乎工作。線程一直停止。我究竟做錯了什麼? –

+0

鎖(塊),鎖(塊[ChunkX,ChunkY]) - 這是一個錯誤的方法。看到我上面的另一個答案。 – user184841

0

好吧,嘗試重寫你的代碼完全類似的東西:

public class Example 
{ 
    private Chunk someVar; 

    private object threadLock = new object(); 

    public void UpdateChunkMeshData() 
    { 

     lock(threadLock){ someVar = .... } 

    } 
} 

首先,先從簡單的代碼與2-4線,以實現正確的方法你的程序工作。你的線程可能會因爲僵局而停下來。

相關問題