Sunday, March 27, 2011

Threading issues..

I'm having an issue with unloading chunks and it's related to threading.

When I unload a chunk, I need to remove all the cubes from the global cube pool.  I'm currently storing those cubes inside a public static Dictionary<Vector3, cube> named, appropriately, allCubes.  allCubes is inside of a static class named gameData so I can access it from wherever I need.  The Vector3 key in allCubes is the location of the cube itself.  So to make a long story short, the cube at 0,0,0 has the key of Vector3(0,0,0) and I reference it using allCubes[Vector3(0,0,0)].whateverINeed.

Most of the time, all I'm doing is reading this Dictionary and adding to it when I create a new chunk.  Now that I'm working on unloading chunks, I need to remove the cubes from that Dictionary.  If there was no threading, it would be a simple matter of removing it and not thinking twice.  Unfortunately with threading, life is not that easy.  If I pull a cube from the dictionary while I'm iterating through it, I'm going to have an exception thrown.  I've been trying to use the lock() method but that doesn't seem to help. 

Anyway, I thought I knew enough about threading to get by, but clearly that's not the case.  I'll be focusing on that for the week and probably won't go forward until I figure this out.

So until then..

2 comments:

Anonymous said...

Multithreading can make code harder to maintain and debug. It can also degrade performance due to locks or the need to copy data structures across threads.
You can arrive at the same result by iteratively generating your chunks. For example:
Update()
{
if (chunk.IsBeingGenerated)
chunk.DoABitMoreWork();
}

C#'s yield return keyword might help here.
I thought it may be worth considering.

Roy said...

I actually solved the issue.. just been too busy the last few days to post up my solution.

I'll post it up tonight so you can see. I agree that if implemented poorly, threading can be a bad thing. In this case, though, when the user needs to be able to keep exploring while a new chunk is being generated threading makes a lot of sense.