PocketMatrix forums

A read-only archive of the PocketMatrix forums (2001–2014). Posting and accounts are closed.

Single threaded app fix

Hello all. I have been developing my Pocket PC game on windows happily for several months with zero bugs, I squash them as I find them. Then I made the port to gapidraw and then all kinds of weird bugs started popping up.

At first I thought it was something I might have missed since my game is running slower on the ppc, but then I thought about it and my game is totally event driven and the only other thread is my sound thread, so they should run EXACTLY the same no matter what the processor speed, except for the frame rate of course.

Well I started poking around in CGapiApplication and low and behold it has a multithreaded draw function. I could see why you might want this but it is really not necessary since you can happily put your draw call in the message loop, I am getting over 400fps on my desktop app doing this.

So now my app is crashing in all sorts of weird places since it was designed for single threaded running. So to fix this I modified CGapiApplication to use some critical sections when drawing and dispatching messages, I guess I could also ditch the draw thread which would free up some resources for ce.

Anyways if anyone wants the code I can post it, pretty simple actually, just put a cs around the message loop parts and the processnextframe call.
mm40: If your application crashes due to the multithreaded architecture of GapiApplication you most probably have a bad design.

You should never draw to the display or surfaces in direct response to a windows message. This will lock up the entire system and is considered bad coding habit. Instead, you should set flags in response to user input and deal with it later. In GapiDraw you should never draw to the display outside the ProcessNextFrame() function.

I would most definitely recommend that you remove your drawing code from the messaging loop and place it in ProcessNextFrame().
Sorry sbl, maybe I wasn't clear in my first post, I am not drawing the function in response to a windows message, but during the idle time when waiting for a message. As in the loop below...

Code:
while( running )
{
draw();

while( PeekMessage(&message,wnd,0,0,PM_REMOVE) )
{
TranslateMessage(&message);
DispatchMessage(&message);
}
}


And it is not bad design, just lack of design why my app crashed due the multithreaded gapidrawapplication base class, you can easily make this class single threaded while reducing system resources and not losing any speed, it will actually gain speed. And the code will be a lot simpler, but I digress.

I could add all kind of critical sections to my code to protect it from the multithreaded nature of gapidrawapplication, but there is little point since 99% of pcs and 100% of pocketpcs have 1 pocessor and will execute the code sequentially anyways.

I have delt with multithreaded issues in my professional career quite often, and learned that it is much easier to just trick the app to be single threaded by placing a few critical sections in key areas, it runs the exact same speed and with no more crashes :)

And I posted this not to suggest you change gapidrawapplication, just to let other people know who may be experiencing strange crashes after porting from a single threaded app.
ok! :)

The multithreading is mostly there so that the game will run nice when windowed on stationary PCs (and not lock up when the user resizes another window etc)...

What you could have done is simply place Draw() inside ProcessNextFrame() and avoid using critical sections etc...
The code I posted is what my original app looked like. For the GapiDraw one I did place my draw() function inside ProcessNextFrame. You still need critical sections protecting it because in my code above WinProc and draw are guarenteed to not be called at the same time, because the loop is either drawing or posting messages.

But in GapiDrawApplication there is another thread that is created, so WinProc and ProcessNextFrame (which includes my draw) can be called at the same time. This is why my app was crashing, I expect and require that WinProc and ProcessNextFrame be called separate, this is why I need critical sections.

Your suggestions of posting input and handling it later would work fine, it is just a little easier to add 5 lines of code for critical sections, than queing and dequing another message buffer on top of the windows message buffer.
Very true... Multiple queues is unavoidable, with critical sections that follows.

Actually, the best solution would probably be to provide both multitthreaded + singlethreaded GapiApplications.. I'll see what I can wrap up in the next beta...

Thanks for the comments + feedback.
Pejo Software - Per · 12 Mar 2003, 23:15 UTC
You can use GapiDraw without using GapiApplication.
So if you are porting a single threaded PC game it might require less time if you just use basic GapiDraw.
Johan, perhaps it would be good to more clearly emphasize that GapiApplication is multithreaded in the documentation and the samples. I think that it is really bad if you are implemnting something in a multithreaded system when you think it is single threaded. Now when I come to think of it having a singlethread option might also give you a hint that you are using multiple threads otherwise :) .
PejoSoftware wrote:
Johan, perhaps it would be good to more clearly emphasize that GapiApplication is multithreaded in the documentation and the samples.


You ain't kidding, I consider threads to be a bit of an overkill for most processes so naturally didn't suspect it all when I first started using GD. After pulling my hair out from some really insane sort of bugs (insane in the single thread mindset) I finally realized the problem.
mm40: I'm interested on converting my game to a single threaded application, can you show me which part do I have to change? Any sample codes? I'm using GapiDrawApplication too. This maybe the answer to further improve my game's performance so I'll give it a shot. Thanks.
sure thing, this would be much better implemented by not creating the thread in the first place as i mention in a previous post, but this was quicker...


add a cs to CGapiApplication (105)
Code:

CRITICAL_SECTION m_cs; // critical section to prevent draw thread and message threads from overlapping



init the cs in CGapiApplication::CGapiApplication (178)
Code:

::InitializeCriticalSection(&m_cs);


free the cs in CGapiApplication::~CGapiApplication() (189)

Code:

::DeleteCriticalSection(&m_cs);


in CGapiApplication::Run() change the WAIT_TIMEOUT case statement to look like this (307)
Code:

case WAIT_TIMEOUT :
{
// Timeout or a Windows message has arrived.
::EnterCriticalSection(&m_cs);
BOOL bPeek = ::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
::LeaveCriticalSection(&m_cs);

while(bPeek)
{
// Note: While PeekMessage (..., PM_NOREMOVE) + GetMessage(...) may be a
// nicer solution, it will not let through WM_ACTIVATE reliably on PPC2000 devices.
if (WM_QUIT == msg.message)
{
// Request thread to exit and wait for signal
m_bThreadShouldExit = TRUE;
break;
}
::EnterCriticalSection(&m_cs);
::TranslateMessage(&msg);
::DispatchMessage(&msg);
bPeek = ::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE);
::LeaveCriticalSection(&m_cs);
}
}
break;


in CGapiApplication::ThreadFunc(LPVOID pParam) add the cs around the ProcessNextFrame call (899)
Code:
::EnterCriticalSection(&pApp->m_cs);
hr = pApp->ProcessNextFrame(pApp->m_backbuffer, dwFrameFlags);
::LeaveCriticalSection(&pApp->m_cs);

if(FAILED(hr))
{
break;
}


then your app is multithreaded acting like a single threaded one since processframe and input messages are serialized, this was all i needed. the numbers in parens above are line numbers after all changes are made, so the line numbers before adding the code will be different.
you said you wanted to add it to improve your games performance, i doubt you will see any difference, so if your doing it just for performance sake i wouldn't bother. in fact you are likely to see a performance decrease if anything, since now the thread must wait for input, and input must wait for the draw frame.

you _might_ see a slight performance gain by not creating the thread in the first place, cause then the os has one less thread to switch in and out of, but i highly doubt it, threads are the least of your worries when you are optimizing your app.
mm40: I have added your code to the current CGapiApplication and renamed it to CGapiApplicationMT. I have now rewritten CGapiApplication so that it is singlethreaded. Those games that need multithreading they can simply replace the superclass CGapiApplication with CGapiApplicationMT. With the critical section fix there should be no difference in how they operate. I did some slight changes though...

*UPDATE* Forget the above.. No changes were made to CGapiApplication, it was simply renamed to CGapiApplicationMT.
Johan,

Am I reading you correctly? You added the critical section code to serialize the input/draw sections to the MT GapiApp class? What would be the point of doing that if you're also releasing a single-thread GapiApp class? I would think this would defeat the whole purpose... Maybe my thinking is skewed however.

Personally I like having a decoupled rendering loop. Means less battery usage from unnecessary rendering cycles hitting the CPU.
Hosed: Sorry, things got a bit wrong here.... :?

No changes were made to CGapiApplication. It was just renamed to CGapiApplicationMT. I then created a new class CGapiAppliation that is single-threaded and 100% identical in use to the multithreaded class. You will find them both in the latest GapiDraw 1.10 distribution.