I am an iOS programmer who is currently using Cocos2d-X to create an Android-iOS app.
I would like to run a function in a background thread (unzipping a file, takes 2-3 seconds), and when it is ready I would like to have a callback to the main thread. During the unzipping there is a small loader animation, which has to run.
This was a really easy task with GCD:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Unzipping here.
dispatch_async(dispatch_get_main_queue(),^{
[self callbackWithResult:result]; // Call some method and pass the result back to main thread
});
});
But here I have to use POSIX which is platform independent. Read some tutorials, but the best I could do is join the background thread into the main thread when it is finished. The problem is that pthread_join blocks the main thread, which stops my loading animation. This was the tutorial I used: https://computing.llnl.gov/tutorials/pthreads/#Joining
(The built-in CCHttpRequest class uses mutexes to add results from the background thread to thread safe array. And a continuously running method in the main thread to check if there is anything in the thread safe array. This is a workaround, but I think is really ugly for such a simple task.)