Reputation: 1615
I'm making a game and I want to run the game logic code and the rendering code on separate threads in hopes of enhancing performance. But for the life of me, I can't figure out how to run a CADisplayLink
in a spawned thread. Right now I'm using NSThread
for multithreading. I've read about NSOperationQue
, but I don't really understand it all that well. Could someone point me in the right direction? This is the code that I'm using now, -logicLoop
and -animationLoop
are both being run on separate threads, so I thought that they would get separate run loops and the CADisplayLinks would be on different threads.
-(void)logicLoop {
NSLog(@"adding");
logicTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateModel)];
logicTimer.frameInterval = kFrameInterval;
[logicTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
-(void)animationLoop {
NSLog(@"animation");
animationTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(renderScene)];
animationTimer.frameInterval = kFrameInterval;
[animationTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
Any ideas?
Should I be using an NSOperationQue
for this? If so, how would I go about that? All I really need is an efficient way to run the game loop and the animation loop on separate threads so that they don't slow each other down, and the game play will appear much smoother.
Thank you!
Upvotes: 4
Views: 3782
Reputation: 3477
For your display link to run, you need a run loop to run. All NSThread
does is spawning a thread, calling your selector and exiting once your selector is done. Here is what this selector should do then:
- (void)threadSelector
{
// initialize CADisplayLink
logicTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateModel)];
logicTimer.frameInterval = kFrameInterval;
[logicTimer addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
// run the loop - this never returns
[[NSRunLoop currentRunLoop] run];
}
Upvotes: 7