0

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.)

SPQR3
  • 647
  • 7
  • 20
  • 1
    Not a Mac programmer, so I don't understand the library calls in your example, but it is *NEVER* possible for one thread to call a function in another thread. Threads can communicate, and one thread can send a message to another asking the recipient to call function f(), but the recipient must expect the message, receive the message, and voluntarily obey it. – Solomon Slow Feb 06 '14 at 16:14
  • Thank you, I think I will _have to_ use a common, thread safe container object to pass messages. – SPQR3 Feb 06 '14 at 16:33
  • Actually, I tried Mac programming *WAY* long ago. Back then, the main() routine of a Mac program usually would sit in a loop, waiting for events, and calling functions as needed to handle the events. There were no "other threads" back then, but if there were, then I could imagine another thread posting a "callback" event. – Solomon Slow Feb 06 '14 at 16:39
  • possible duplicate of [Guaranteed file deletion upon program termination (C/C++)](http://stackoverflow.com/questions/471344/guaranteed-file-deletion-upon-program-termination-c-c) – Paul Sweatte Oct 07 '14 at 23:59

1 Answers1

0

Use this to run your code in main thread of cocos2d:

Director::getInstance()->getScheduler()->performFunctionInCocosThread([]{
    // execution in main thread
});
Dmytro
  • 1,290
  • 17
  • 21