Cocoa Port pt 7 - Threading

When we run 2 timers on the Cocoa run loop, all our app code is still single threaded. If performance was a problem in our game, we would be running into that already. If I had a target device (like an iPhone) that I knew had a single performance characteristic, I would start dialing back the timers until Space Invaders felt funny, then I'd bump them barely back up over that.

When programming for battery life, it is best to do as much work as possible, as fast as possible. If you are on a multi core processor, it would be possible to run the screen refresh and the CPU emulation at the same time by putting one of them on a thread. Cocoa seems to encourage the drawing to remain on the main app loop, so I'm going to put the CPU emulation on a loop.

The modifications are pretty easy. In my startEmulation method, I'll create a thread instead of a timer:

   - (void) startEmulation    
   {    
       [NSThread detachNewThreadSelector:@selector(doCPU) toTarget:self withObject:nil];    
   }    

Now, I'll make the doCPU routine never exit. Prior to updating this code to use Cocoa Automated Reference Counting (ARC), I had to create a NSAutoreleasePool and drain it periodically. When I updated the code to ARC, I just wrap the whole doCPU routine in while (1) and wrap that in a autorelease block. As far as I can find there is no need to periodically drain an autorelease block.

   {    
    @autoreleasepool    
    {    
        while(1)    
        {    
            //contents of old doCPU here    
        }    
    }    
   }    

That's really all there is to it - the cpu is now updating out of phase with the rest of the machine, and then the video updates on it's regular timer. To my eye, it looks like this approach uses less CPU, but it may be because of me tweaking the sleep time of the thread.

You can view the threading source on github under CocoaPart7-Threading.

← Prev: cocoa-port-pt-6---performance   Next: iphone-port-pt-1---project-setup →