views:

627

answers:

3

i have some C# threading program (a game), that stops with a boolean (as most articles recommends).

while (gameContinueRun)
{
  createRound();
  line1;
  line2;
  line3;
  line4;
  endRound();
}

some code lines lock the game and wait until other thread will release it.

lock (stateSync)
{
  Monitor.Wait(stateSync)
}

to stop the thread from another thread i set the boolean to false :

if (cancel)
{
  gameContinueRun= false;
}

everything works nice.. but i still need to wait until the end of the current loop (round).

now, i want to end the loop, to break all work in the middle (abort game). another thing is to be able to restrat the loop (open new round). (or in another words, two things : 1. aborting the game 2. cancel the current round and start a new one..)

i thought about it, and got a couple of ways :

  1. unlock all locks, and check after every code line :

    if (!cancelRound) { line1; } if (!cancelRound) { line2; } if (!cancelRound) { line3; } if (!cancelRound) { line4; }

    not very nice, and very exhausting if one have lots of code lines to cover...

  2. use Thread.Abort(), catching the Exception and resetAbort() if needed.

  3. use goto and labels (which i assume is even uglier then aborting..)

which one is better? or more over, is there a better recommended way? thanks!

A: 

I usually end up writing lots of

if (m_state != GameState.Active) {
    return;
} // if

kind of code.

Maybe you could use custom attribute, similar to that of code access security. And do something like

[RequireState(GameState.Active)]
void DoSomething();
eed3si9n
A: 

It not entirely clear what you are trying to do, but it looks like you want some form of inter-thread communication. However, it is usual for the game loop to control the other threads, not to be controlled itself. So instead you'd have:

function GameLoop
  start threads
  while (continuing game loop)
    tell threads to do something
    wait for threads to finish doing something
  end while
  tell threads to stop
  wait for threads to terminate
end function

Your solution using the lock and Monitor.Wait is unusual and probably not robust enough. I think you need to do some research into multi-threading and maybe tryout some classical problems (the dining philosophers for example) and then redesign your code.

Skizz

Skizz
+1  A: 

Try looking at WaitHandle.WaitAny(WaitHandle[]) method for your locks. Then you can work with arrays of AutoResetEvent or ManualResetEvent - one for exiting and all the rest for the locking. See: http://msdn.microsoft.com/en-us/library/yy12yx1f.aspx

RA