I have a little problem with my game... i have a worker thread for updating and calculating objects (matrices for opengl) in the background.
This static class called "Driver" holds a thread handle and two lists - one for camera's, one for other objects. The "Driver" checks continously for changes of the objects, iteration through the two lists. If an object has changes, its "Calculate()" method is called by the "Driver".
Each time of iteration through one of the Lists, the list is locked:
Monitor.Enter(CameraList);
try{
foreach (BaseCamera Cam in CameraList){
if (!(Cam.isLocked) && (Cam.isCalcRequired())){
Cam.onUpdate();
}
}
}finally{
Monitor.Exit(CameraList);
}
Monitor.Enter(ObjectList);
try{
foreach (BaseObject obj in ObjectList){
if (!(obj.isLocked) && (obj.isCalcRequired())){
obj.onUpdate();
}
}
}finally{
Monitor.Exit(ObjectList);
}
All fine. But sometimes I get a deadlock when adding an object - i call a static "AddObject" method which looks like this:
public static bool AddObject(BaseObject Object){
if (Object.Ident == ObjectIdent.Camera){
Monitor.Enter(CameraList);
try{
CameraList.Add((BaseCamera)Object);
return true;
}finally{
Monitor.Exit(CameraList);
}
}else{
Monitor.Enter(ObjectList);
try{
ObjectList.Add(Object);
return true;
}finally{
Monitor.Exit(ObjectList);
}
}
return false;
}
I think, the deadlock appears, because the WorkerThread iterates to fast and the AddObject function is unable to lock one of the lists. But to solve the problem, i had to add "Thread.Sleep(100)" after updating both lists... is there a simple way to avoid such problems? Sleeping for 100Ms makes everything very laggy ;)
P.s.: I tried other variants with Semaphores and Mutex but none of them solved the deadlock problem =/