Threading issue on Ouya with JavaScript bindings

If this is covered in another forum thread, please point me to it. :slight_smile: I’ve looked but not found anything yet.

I am working on a basic development environment on the Ouya using cocos2d-x 2.2. I’ve gotten a basic game up and running, using the JavaScript bindings, and I have the controller working - mostly.

The problem I am running into is one of random crashes when pressing buttons on the controller. I followed the same model as the other input devices (e.g. touch, keypad), so in theory, they should have the same problem I’m seeing.

After adding a good amount of logging, I have discovered the root cause.

The main application thread sits in a loop and calls the director’s mainloop function. This function calls drawScene and then pops the current shared pool manager. This happens over and over, free-running.

Meanwhile, when buttons on the controller are pressed, Java code calls down into C*+ code via JNI on its own thread. When these events are then packaged up and piped up to the JavaScript code in ScriptingCore, autorelease objects are created and added into the current pool. Since the main app thread is running without any synchronization to these JNI threads, the main app can basically pull the rug out from under the JNI threads by deleting the objects out from under them that are being used. This happens randomly, when the app happens to pop the current pool when a JNI handler is running.
The only solution I can think of is to provide some sort of synchronization object between the main app thread and any JNI thread. Even adding reference counts into the autorelease objects won’t help, because the retain and release methods in CCObject do not use atomic incs and decs, so the bad multi-threading demon raises its head when accessed from multiple threads at once.
Has anyone seen this problem? I have to assume so, since it’s a basic flaw in the path from Java to C*+ JS with the main app loop running in parallel.

So, more importantly, is there any known solution? I’m leaning toward a global mutex to synchronize the two parts of code, but I’d prefer something more elegant if possible.

I’ve attached a file showing the logging for one crash. I hope most of it is self-explanatory. The a… b… c…, etc lines are scattered through js_callFunc. The “e…” and “f…” ones bracket the call to CCCallFuncN::create.

Any help or thoughts appreciated! Thanks much.


TextFile14.txt.zip (18.9 KB)

Here is one more run. You can clearly see the CallFuncWrapper being deleted before js_callFunc exits, resulting in a seg fault.