Using std::thread and userdefault on android

Hi,

While developing a game for iOS and Android, I ran into an issue:

I want to use c++ std::thread to write some data to UserDefault. The problem is, the app crashes with the following error:
D/dalvikvm(13181): threadid=13: thread exiting, not yet detached (count=0)
D/dalvikvm(13181): threadid=13: thread exiting, not yet detached (count=1)
E/dalvikvm(13181): threadid=13: native thread exited without detaching

To start the thread, I use the following code (which works perfectly on windows and iOS):

std::thread backgroundThread(&Example::clearAllLevelProgressInBackground, this);
backgroundThread.detach();

The clearAllLevelProgressInBackground is just something like the following code:

auto userDefault = UserDefault::getInstance();
//a lot of:
userDefault->setIntegerFor.....
//etc.
userDefault->flush();
getScheduler()->schedule(schedule_selector(Example::afterLevelsCleared), this, 0, 0, 0, false);

I don’t know what the issue is, as I do not retain or release anything (the manual warned about this). Without the thread the code works fine, but the UI freezes for a while, which is why I used a thread. Does anybody know what this is?

Read those threads:

That means that you are somehow exiting a thread without detaching the JNI environment from that thread
https://groups.google.com/forum/#!topic/apportable-discuss/plv-BGrZtwY

https://github.com/openfl/lime/issues/83
https://github.com/Hasufel/lime/commit/fe2e0c56a3e4239b56fb0dbe1c4d25b004df68dd

The issue was doing stuff with UserDefault in the thread (probable some JNI interaction in the cocos2d classes responsible for saving the userdefault values). It’s not possible to write to userdefault in a different thread without changing core code I guess. Is there another way to fix this without changing framework code?