9

In an attempt to create a loading bar for an iPhone game I'm developing (using Cocos2D), I wanted to use a multithreaded approach.

One thread shows a loading screen and runs the main application event loop while a new thread silently loads all the Sprites in the background (through spriteWithFile) and then adds them to a layer.

I create the new thread using NSThread's detachNewThreadSelector method (which sends updates of the loading status to the main thread via performSelectorOnMainThread).

The problem I'm facing is that any OpenGL calls (such as those found within the spriteWithFile method) in the new thread die with a BUS ERROR or memory access error of some sort. I'm assuming this is because both threads are attempting to make OpenGL calls at the same time or the new thread is unaware of the OpenGL context.

What has to be done to allow multiple threads to make OpenGL calls on the iPhone using Cocos2D-iPhone.

4 Answers 4

3

For the record, the new thread needs to execute the following two lines to be able to use the OpenGL API from a concurrent thread:

EAGLContext *k_context = [[[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1 sharegroup:[[[[Director sharedDirector] openGLView] context] sharegroup]] autorelease];
[EAGLContext setCurrentContext:k_context];

This is now made obsolete by the addImageAsync method provided by the TextureMgr class in Cocos2D 0.8.x onwards that does asynchronous texture loading for you.

2

I want to do this too.

I'm starting from this thread.

PS: This answer is very old, now I'm not sure that asynchronous texture loading is as useful as it once was since iOS5 added "free" texture uploads via CVOpenGLESTextureCaches. Sure you still can (& should) load your assets in a secondary thread, but giving that thread an EAGLContext doesn't seem as necessary now.

1
  • Link in first answer: 1. I get malware warning from browser. When I still say to ignore it 2. I get 404. Jul 17, 2012 at 1:46
2

Apple has some good guidelines for multithreaded OpenGL here.

-1

Cocos2d best practices recommend against using NSTimer and I assume the same applies to threads as well. You should probably use Cocos' Timer object. This will leave the thread management to Cocos and should also let you access the correct graphics context. HTH.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.